We’re rewarding the question askers & reputations are being recalculated! Read more.
371

How to conditionally do something if a command succeeded or failed That's exactly what bash's if statement does: if command ; then echo "Command succeeded" else echo "Command failed" fi Adding information from comments: you don't need to use the [ ... ] syntax in this case. [ is itself a command, very nearly equivalent to test. It's probably the ...


345

These are called shell operators and yes, there are more of them. I will give a brief overview of the most common among the two major classes, control operators and redirection operators, and how they work with respect to the bash shell. A. Control operators In the shell command language, a token that performs a control function. It is one of the ...


144

The right side of && will only be evaluated if the exit status of the left side is zero (i.e. true). || is the opposite: it will evaluate the right side only if the left side exit status is non-zero (i.e. false). You can consider [ ... ] to be a program with a return value. If the test inside evaluates to true, it returns zero; it returns nonzero ...


134

For small things that you want to happen if a shell command works, you can use the && construct: rm -rf somedir && trace_output "Removed the directory" Similarly for small things that you want to happen when a shell command fails, you can use ||: rm -rf somedir || exit_on_error "Failed to remove the directory" Or both rm -rf somedir &...


62

Warning regarding ‘>’ Unix beginners who have just learned about I/O redirection (< and >) often try things like command … input_file > the_same_file or command … < file > the_same_file or, almost equivalently, cat file | command … > the_same_file (grep, sed, cut, sort, and spell are examples of commands that people are tempted ...


61

Here's my cheat sheet: "A ; B" Run A and then B, regardless of success of A "A && B" Run B if A succeeded "A || B" Run B if A failed "A &" Run A in background.


58

You can use read: read -n1 -r -p "Press space to continue..." key if [ "$key" = '' ]; then # Space pressed, do something # echo [$key] is empty when SPACE is pressed # uncomment to trace else # Anything else pressed, do whatever else. # echo [$key] not empty fi


47

This worked for me: command && echo "OK" || echo "NOK" if command succeeds, then echo "OK" is executed, and since it's successful, execution stops there. Otherwise, && is skipped, and echo "NOK" is executed.


46

The method discussed in this SO Q&A is likely the best candidate for an alternative to the pause behavior that you're accustom to on Windows when doing BAT files. $ read -rsp $'Press any key to continue...\n' -n1 key Example Here I am running the above and then simply pressing any key, in this case the D key. $ read -rsp $'Press any key to continue......


29

More observations on ;, &, ( and ) Note that some of the commands in terdon’s answer may be null.  For example, you can say command1 ; (with no command2).  This is equivalent to command1 (i.e., it simply runs command1 in the foreground and waits for it to complete.  Comparably, command1 & (with no command2) will launch command1 in the ...


29

Most people find it easier to comprehend the if ... then ... else ... fi form. For the a && b || c, you have to be sure that b returns true. This is a cause of subtle bugs and is a good reason to avoid this style. If b doesn't return true these are not the same. $ if true; then false ; else echo boom ; fi $ true && false || echo boom ...


28

to expand on @Shawn-j-Goff's answer from above, && is a logical AND, and || is a logical OR. See this part of the Advanced Bash Scripting Guide. Some of the contents from the link for user reference as below. && AND if [ $condition1 ] && [ $condition2 ] # Same as: if [ $condition1 -a $condition2 ] # Returns true if both ...


27

In bash or ksh, put the file names in an array, and iterate over that array in reverse order. files=(/var/logs/foo*.log) for ((i=${#files[@]}-1; i>=0; i--)); do bar "${files[$i]}" done The code above also works in zsh if the ksh_arrays option is set (it is in ksh emulation mode). There's a simpler method in zsh, which is to reverse the order of the ...


27

for loops loop on the positional parameters if no in value1 value2... part is specified in all Bourne-like shells. That was already the case in the Bourne shell from the late 70s, though in the Bourne shell, you'd need to omit that ; (you can also use for i do (except in some old ash versions where you need a newline before the do)). See What is the ...


26

No, constructions if A; then B; else C; fi and A && B || C are not equivalent. With if A; then B; else C; fi, command A is always evaluated and executed (at least an attempt to execute it is made) and then either command B or command C are evaluated and executed. With A && B || C, it's the same for commands A and B but different for C: ...


25

You need to interpolate the $testseq variable with one of the following ways: $file == *_"$testseq"_* (here $testseq considered as a fixed string) $file == *_${testseq}_* (here $testseq considered as a pattern). Or the _ immediately after the variable's name will be taken as part of the variable's name (it's a valid character in a variable name).


20

You don't need two loops; you just need to read from two files in the one loop. while read compareFile1 <&3 && read compareFile2 <&4; do if [[ ! $server =~ [^[:space:]] ]] ; then #empty line exception continue fi echo "Comparing file - $compareFile" if diff "$compareFile1" "$compareFile2" >/dev/null ; then ...


20

file="JetConst_reco_allconst_4j2t.png" testseq="gen" case "$file" in *_"$testseq"_*) echo 'True' ;; *) echo 'False' esac Using case ... esac is one of the simplest ways to perform a pattern match in a portable way. It works as a "switch" statement in other languages (bash, zsh, and ksh93 also allows you to do fall-through in various ...


20

This is the default behavior, yes. It is documented in the help of the for keyword: terdon@tpad ~ $ help for for: for NAME [in WORDS ... ] ; do COMMANDS; done Execute commands for each member in a list. The `for' loop executes a sequence of commands for each member in a list of items. If `in WORDS ...;' is not present, then `in "$@"' is ...


17

There isn't a do...while or do...until loop, but the same thing can be accomplished like this: while true; do ... condition || break done for until: until false; do ... condition && break done


17

I think the case/esac construct fits well here. #!/bin/bash case "`date +%j`" in 40) name=Osvaldo ;; 47) name=Berenice ;; 54) name=Nizaá ;; *) exit ;; esac echo "Esta semana le toca preparar el café a ${name}" \ | mail -s 'Café' mailgroup@somedomain.mx Note: if the same person needs to make coffee several times, you can aggregate tests with |: ...


17

Commands in a pipeline run concurrently, that's the whole point of pipes, and inter-process communication mechanism. In: cmd1 | cmd2 cmd1 and cmd2 are started at the same time, cmd2 processes the data that cmd1 writes as it comes. If you wanted cmd2 to be started only if cmd1 had failed, you'd have to start cmd2 after cmd1 has finished and reported its ...


15

From "help continue": continue: continue [n] Resume for, while, or until loops. Resumes the next iteration of the enclosing FOR, WHILE or UNTIL loop. If N is specified, resumes the Nth enclosing loop. Exit Status: The exit status is 0 unless N is not greater than or equal to 1. So you want continue or continue 1 to go to the next ...


14

That is a feature of the for compound command, as described by help for: for: for NAME [in WORDS ... ] ; do COMMANDS; done Execute commands for each member in a list. The for loop executes a sequence of commands for each member in a list of items. If in WORDS ...; is not present, then in "$@" is assumed. For each element in WORDS, NAME is ...


14

ssh user@1.2.3.4 "ls /home/somefile" || { echo "File does not exist"; exit 1; } This is called a compound command. From man bash: Compound Commands A compound command is one of the following: (list) list is executed in a subshell environment (see COMMAND EXECU‐ TION ENVIRONMENT below). Variable assignments and builtin ...


13

From my experience I use the && and || to reduce an if statement to a single line. Say we are looking for a file called /root/Sample.txt then the traditional iteration would be as follows in shell: if [ -f /root/Sample.txt ] then echo "file found" else echo "file not found" fi These 6 lines can be reduced to a single line: [[ -f /root/...


12

for x; do … is a shortcut for for x in "$@"; do …: it iterates over the positional parameters. If it loops four times, it means you have four positional parameters ($1 through $4).


Only top voted, non community-wiki answers of a minimum length are eligible