if [ "$(ls -A $variable)" ]
will be true if the command ls -A $variable
returns any output - the $()
"operator" (or command substitution) executes the command and returns it's output.
how does this bash operation work in shell scipt
Question
Hello i have come across a bash operation that i am finding hard to understand i have looked through the bash reference manual but have had no luck figuring out how this operation works.
i am having trouble understanding what the operation does i know ls -A will list all files including hidden files and the variable already has information stored within it, so what does the $() operation do.
this is the operation.
if [ "$(ls -A $variable)" ]
thanks for the feedback
La solution
Autres conseils
1) See the manpage of ls
:
-A, --almost-all do not list implied . and ..
2) The $()
is an equivalent of backquotes (``) also called "command substitution". This corresponds to a sub-process execution.
In other words, the output of your command is catched by parentheses and could be affected to a variable like this :
var=$(ls -A)
echo "$var" # will print the output of ls -A
3) [ "string" ]
or [[ "string" ]]
or test string
is equivalent of using -n option :
$ [[ "" ]] && echo "yes"
$ [[ "something" ]] && echo "yes"
yes
$ [[ -n "something" ]] && echo "yes"
yes
See man test
:
-n STRING the length of STRING is nonzero
So your command allows to check if the content of the current directory is not empty.