Can a conditional statement be used inside a command in bash? [duplicate] - bash

This question already has answers here:
Ternary operator (?:) in Bash
(23 answers)
Bash command groups: Why do curly braces require a semicolon?
(1 answer)
Closed 2 years ago.
Can a conditional statement be inserted in, for example, a print command like echo with bash?
E.g. (does not work)
$ cat t.sh
#!/bin/bash
string1="It's a "
string2opt1="beautiful"
string2opt2="gross"
string3=" day."
read c
echo -n "$string1 $( [[ $c -eq 0 ]] && { echo -n "$string2opt1" } || { echo "$string2opt2" } ) $string3"
I know that this is possible with semicolons/non-one-liners; I am just wondering if there is a more elegant or accepted way of doing this.

To clarify, you want to achieve this:
#!/bin/bash
string1="It's a"
string2opt1="beautiful"
string2opt2="gross"
string3="day."
read -r c
if [[ $c -eq 0 ]]; then
echo "$string1" "$string2opt1" "$string3"
else
echo "$string1" "$string2opt2" "$string3"
fi
but in a one-liner. Does this work for you?
#!/bin/bash
string1="It's a"
string2opt1="beautiful"
string2opt2="gross"
string3="day."
read -r c
echo "$string1" "$([[ $c -eq 0 ]] && echo "$string2opt1" || echo "$string2opt2")" "$string3"

Related

How can i shorten long multiple checking variable in bash? [duplicate]

This question already has answers here:
How do I parse command line arguments in Bash?
(40 answers)
Command line arguments in Bash [duplicate]
(2 answers)
Closed 2 years ago.
i want to check multiple variables in bash but end up too much, is there any way to shorten this
i end up like this
if [[ $1 == -a || $2 == -a || $3 = -a ]] && [[ $1 == -b || $2 == -b || $3 = -b ]] && [[ $1 == -c || $2 == -c || $3 = -c ]] && [ $# -eq 4 ]; then
echo "insert some words"
exit
fi
i've tried this to shorten it but won't work
a=-a
b=-b
c=-c
if [[ ${#:1:3} == $a || ${#:1:3} == $b || ${#:1:3} == $c ]] && [ $# -eq 4 ]; then
echo "insert some words"
exit
fi
is there any way to shorten this?
thanks in advance!
Options with getopts
while getopts ":a:b:c:" opt; do
case $opt in
(a) a=$OPTARG;;
(b) b=$OPTARG;;
(c) c=$OPTARG;;
esac
done
echo $a $b $c
Or with just case
while [[ $# ]]; do
case $1 in
(-a) a=$2;;
(-b) b=$2;;
(-c) c=$2;;
esac; shift
done
echo $a $b $c

How to check if pipe content (stdout) is empty in bash [duplicate]

This question already has answers here:
Test if a command outputs an empty string
(13 answers)
Closed 4 years ago.
Some Example:
I've a shellscript where I want to check if a the stdout of a command is empty.
So I can do
if [[ $( whateverbin | wc -c) == 0 ]] ; then
echo no content
fi
But is there no direct command, to check this? Something like :
if whateverbin | checkifstdinisempty ; then
echo no content
fi
You could use the -z conditional expression to test if a string is empty:
if [[ -z $(ls) ]]; then echo "ls returned nothing"; fi
When you run it on an empty result, the branch gets executed:
if [[ -z $(cat non-existing-file) ]]; then echo "there was no result"; fi
Just try to read exactly one character; on no input, read will fail.
if ! whateverbin | IFS= read -n 1; then
echo "No output"
fi
If read fails, the entire pipeline fails, and the ! negates the non-zero exit status so that the entire condition succeeds.
[[ `echo` ]] && echo output found || echo no output
--> no output
[[ `echo something` ]] && echo output found || echo no output
--> output found
With if :
if [ `echo` ] ; then echo ouput found; else echo no output; fi

Using if conditions in shellscripting [duplicate]

This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Closed 6 years ago.
read A
if [["$A" == 'Y' -o "$A" =='y']]
then echo "YES"
else echo "NO"
fi
I am very new to shell scripting.basically, i am trying to check if the input is Y or y.
I am getting the following error which I am not able to debug.
solution.sh: line 2: [[Y: command not found
Thanks.
You are missing space after [[
The if should be like
if [[ "$A" == 'Y' || "$A" == 'y' ]]
The [[ ]] is an extended test command, like any command it should be separated from others by spaces
Add proper space inside the square brackets and after the ==:
read A
if [ "$A" == 'Y' -o "$A" == 'y' ]; then
echo "YES";
else
echo "NO";
fi
Note that to use -o you ought to use test command, which uses single brackets.
If you use [[ ]], with double brackets, you must use || instead of -o:
read A
if [[ "$A" == 'Y' || "$A" == 'y' ]]; then
echo "YES";
else
echo "NO";
fi

Bad substitution error in ksh [duplicate]

This question already has answers here:
Cannot debug simple ksh programme
(2 answers)
Closed 8 years ago.
The following KornShell (ksh) script should check if the string is a palindrome. I am using ksh88, not ksh93.
#!/bin/ksh
strtochk="naman"
ispalindrome="true"
len=${#strtochk}
i=0
j=$((${#strtochk} - 1))
halflen=$len/2
print $halflen
while ((i < $halflen))
do
if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then
(i++)
(j--)
else
ispalindrome="false"
break
fi
done
print ispalindrome
But I am getting bad substitution error at the following line : if [[ ${strtochk:i:1} == ${strtochk:j:1} ]];then
Can someone please let me know what I am doing wrong?
The substring syntax in ${strtochk:i:1} and ${strtochk:j:1} is not available in ksh88. Either upgrade to ksh93, or use another language like awk or bash.
You can replace your test with this portable line:
if [ "$(printf "%s" "$strtochk" | cut -c $i)" =
"$(printf "%s" "$strtochk" | cut -c $j)" ]; then
You also need to replace the dubious
halflen=$len/2
with
halflen=$((len/2))
and the ksh93/bash syntax:
$((i++))
$((j--))
with this ksh88 one:
i=$((i+1))
j=$((j-1))
How about this KornShell (ksh) script for checking if an input string is a palindrome.
isPalindrome.ksh
#!/bin/ksh
#-----------
#---Main----
#-----------
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"
echo Enter the string
read s
echo $s > temp
rvs="$(rev temp)"
if [ $s = $rvs ]; then
echo "$s is a palindrome"
else
echo "$s is not a palindrome"
fi
echo "Exiting: ${PWD}/${0}"

C style arithmetic with floating point values in Bash [duplicate]

This question already has answers here:
How do I use floating-point arithmetic in bash?
(23 answers)
Closed 4 years ago.
How can I have the right result from this bash script?
#!/bin/bash
echo $(( 1/2 ))
I get 0 as result! So I tried to use these but without success:
$ echo $(( 1/2.0 ))
bash: 1/2.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
$ echo $(( 1.0/2 ))
bash: 1.0/2 : syntax error: invalid arithmetic operator (error token is ".0/2 ")
bash is not the right tool alone to use floats, you should use bc with it :
bc <<< "scale=2; 1/2"
.50
If you need to store the result in a variable :
res=$(bc <<< "scale=2; 1/2")
echo $res
I once stumbled on a nice piece of code, which is somewhat utilizing suggestion sputnick made, but wraps it around a bash function:
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
Then, you can use it as:
c=$(float_eval "$a / $b")

Resources