I'm very simply wondering if, in a bash script,
a new line is functionally 100% equivalent to &&
?
e.g.:
#!/bin/bash
7z x "${file}"
mv "${file}" "${new_file}"
vs
#!/bin/bash
7z x "${file}" && mv "${file}" "${new_file}"
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
1 Answer 1
No: &&
only runs the command following it if the command preceding it succeeds. Thus
7z x "${file}" && mv "${file}" "${new_file}"
only renames the file if 7z
completes successfully, whereas
7z x "${file}"
mv "${file}" "${new_file}"
will run mv
in all cases (and fail if ${file}
doesn’t exist).
See What are the shell's control and redirection operators? for details (in particular, it describes how new lines are also not quite the same as ;
).
-
1Since
$file
is a parameter that should be7z x -- "$file"
andmv -- "$file" "$new_file"
(NB some people seem to think that${var}
is equivalent to"$var"
)Chris Davies– Chris Davies2024年03月09日 19:35:41 +00:00Commented Mar 9, 2024 at 19:35 -
what if we add
set -e
at the beginning of the second example? Would it then behave the same as the first snippet?Meto– Meto2024年03月09日 21:42:47 +00:00Commented Mar 9, 2024 at 21:42 -
Isn't that a good practice to put curly braces around vars? nickjanetakis.com/blog/…s.k– s.k2024年03月09日 22:33:13 +00:00Commented Mar 9, 2024 at 22:33
-
@s.k Do both. Writing
$A
as"$A"
prevents shell expandingA
into multiple words. Writing$A_B
as${A}_B
prevents shell trying to expand an unknown variableA_B
instead of expandingA
and appending_B
. Many of the extended expansions (array, substring, trimming) require the{..}
to control the internal syntax.Paul_Pedant– Paul_Pedant2024年03月10日 10:11:44 +00:00Commented Mar 10, 2024 at 10:11 -
1@Meto not quite —
7z ... && mv ...
will only runmv
if7z
succeeds, but will continue running aftermv
if7z
fails; whereasset -e; 7z ...; mv ...
will exit if any command fails, includingmv
, and anything followingmv
won’t run if7z
ormv
fails.Stephen Kitt– Stephen Kitt2024年03月10日 12:46:31 +00:00Commented Mar 10, 2024 at 12:46