I'm getting familiar with all about Linux & shell/bash scripting.

I'm configuring a backup script & it will compress an entire directory. I want to know if I have to print the variable where the command that will compress will be allocated or only by setting it to the variable will execute it?

I have this:

x1=$(tar cfz "/dir_destination" "/dir_to_compress/")
echo "$x1"

I'm wondering if I could safely remove 'echo' line.


The $() syntax is called command substitution and the shell treats it by first executing the command inside the parentheses then assigning its stdout (with trailing newlines removed) to x1.

In other words, the command is executed even before you echo "$x1".

|improve this answer|||||
  • Perfect, so, if I understood the links you put above, It's more recommended to use quotes despite I'm not using any coma in the command? Or quotes are necessary for x1 to execute the command? – tachomi Jun 3 '14 at 21:24
  • @tachomi The quotes are necessary in case the output of the command has any whitespace. Without quotes, Bash would consider that the command's output up to the first whitespace character is what you are trying to assign to x1 and it will consider what comes after as additional commands. – Joseph R. Jun 3 '14 at 21:34
  • So while 'tar' command commonly doesn't have an output, quotes are not necessary down here. Will be necessary for this kind of usage?: print=$(echo nice to meet you) - WRONG print="$(echo nice to meet you)" - RIGHT – tachomi Jun 3 '14 at 21:41
  • @tachomi Yes, if the command has no output, the quotes are unnecessary, but so is the command substitution. What do you think to gain by assigning a null string to x1? – Joseph R. Jun 3 '14 at 21:42
  • Only the creation of the .tar.gz file to then send it using scp to a backup server :D – tachomi Jun 3 '14 at 21:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.