I wonder what the difference between
"echo 'hello'; ls"
and
"echo 'hello' && ls"
is? they both do the same thing
I wonder what the difference between
"echo 'hello'; ls"
and
"echo 'hello' && ls"
is? they both do the same thing
Here, they do the same.
But take an other example:
cp file target && ls
cp file target; ls
In the first case, ls would only be executed if cp succeeds.
In the second case, no matter if cp fails or succeeds, ls will always be executed.
The && is the logical AND operator. The idea in its use in command1 && command2 is that command2 is only evaluated/run if command1 was successful. So here ls will only be run if the echo command returned successful (which will always be the case here, but you never know ;-). You could also write this as:
if echo 'hello'
then
ls
fi
The semicolon just delimits two commands. So you could also write echo 'hello' ; ls as:
echo 'hello'
ls
Thus ls will also be executed even when echo fails.
BTW, successful in this context means that the program was exited with something like exit(0) and thus returned 0 as a return code (the $? shell variable tells you the return status of the last executed command).
So here ls will only be run if the echo command returned successful (which will always be the case here, but you never know ;-).
Well, not always. For example, the standard output stream may be unwritable
:; ( echo "foo" && touch /tmp/succeeded) >/dev/full
bash: echo: write error: No space left on device
:; ls -l /tmp/succeeded
ls: cannot access /tmp/succeeded: No such file or directory
(This should have been a comment not an answer, but stackoverflow won't let me post comments until I have more karma. Sorry)
"echo 'hello' && ls" means : execute "ls" if "echo 'hello'" runs successfully. To understand what is "successful" in bash. Try this :
bash> cd /
bash> echo $?
if the previous command runs successfully, you should see 0
After that, try this :
bash> asdfdf
bash> echo $?
You should see a random value between 1 and 255. This means previous command didn't run successfully
On the other hand, "echo 'hello'; ls" means execute "ls" whether "echo 'hello'" runs successfully or not.