質問

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

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top