Shell scripting interview questions
40 questions with answers. 1,031 open jobs in India ask for Shell scripting.
What does " 2>&1 " mean?
File descriptor 1 is the standard output (
stdout).
File descriptor 2 is the standard error (stderr).At first,
2>1may look like a good way to redirectstderrtostdout. However, it will actually be interpreted as "redirectstderrto a file named1".&indicates that what follows and precedes is a file descriptor, and not a filename. Thus, we use2>&1. Consider>&to be a redirect merger operator.From Stack Overflow: asked by Tristan Havelick, answered by Ayman Hourieh (CC BY-SA 4.0)
Difference between sh and Bash
What is sh?
sh(or the Shell Command Language) is a programming language described by the POSIX standard. It has many implementations (ksh88, Dash, etc.). Bash can also be considered an implementation ofsh(see below).Because
shis a specification, not an implementation,/bin/shis a symbolic link (or a hard link) to an actual implementation on most POSIX systems.What is Bash?
Bash started as an
sh-compatible implementation (although it predates the POSIX standard by a few years), but as time passed it has acquired many extensions. Many of these extensions may change the behavior of valid POSIX shell scripts, so by itself Bash is not a valid POSIX shell. Rather, it is a dialect of the POSIX shell language.Bash supports a
--posixswitch, which makes it more POSIX-compliant. It also tries to mimic POSIX if invoked assh.Is sh = bash?
For a long time,
/bin/shused to point to/bin/bashon most GNU/Linux systems. As a result, it had almost become safe to ignore the difference between the two. But that started to change recently.Some popular examples of systems where
/bin/shdoes not point to/bin/bash(and on some of which/bin/bashmay not even exist) are:Modern Debian and Ubuntu systems, which symbolic links executable
shto executabledashby default;Busybox, which is usually run during the Linux system boot time as part of initramfs. It uses the ash shell implementation.
BSD systems, and in general any non-Linux systems. OpenBSD uses
pdksh, a descendant of the KornShell (executableksh). FreeBSD'sshis a descendant of the original Unix Bourne shell. Solaris has its ownshwhich for a long time was not POSIX-compliant; a free implementation is available from the Heirloom project.
How can you find out what
/bin/shpoints to on your system?The complication is that
/bin/shcould be a symbolic link or a hard link. If it's a symbolic link, a portable way to resolve it is:file -h /bin/shOutput:
/bin/sh: symbolic link to bashIf it's a hard link, try
find -L /bin -samefile /bin/shOutput:
/bin/sh /bin/bashRead the rest at the sourceFrom Stack Overflow: asked by Weiwei Yang, answered by Roman Cheplyaka (CC BY-SA 4.0)
What is the preferred Bash shebang ("#!")?
You should use
#!/usr/bin/env bashfor portability: Different *nixes putbashin different places, and using/usr/bin/envis a workaround to run the firstbashfound on thePATH.And
shis notbash.From Stack Overflow: asked by bgibson, answered by l0b0 (CC BY-SA 4.0)
What does 'set -e' mean in a Bash script?
From
help setand Bash Reference Documentation: The Set Builtin:-e Exit immediately if a command exits with a non-zero status.But it's considered bad practice by some (Bash FAQ and IRC Freenode #bash FAQ authors). It's recommended to use:
trap 'do_something' ERRto run
do_somethingfunction when errors occur.See Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?
From Stack Overflow: asked by AndreaNobili, answered by Gilles Quénot (CC BY-SA 4.0)
How do I get the directory where a Bash script is located from within the script itself?
#!/usr/bin/env bash SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
#!/usr/bin/env bash get_script_dir() { local SOURCE_PATH="${BASH_SOURCE[0]}" local SYMLINK_DIR local SCRIPT_DIR # Resolve symlinks recursively while [ -L "$SOURCE_PATH" ]; do # Get symlink directory SYMLINK_DIR="$( cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd )" # Resolve symlink target (relative or absolute) SOURCE_PATH="$(readlink "$SOURCE_PATH")" # Check if candidate path is relative or absolute if [[ $SOURCE_PATH != /* ]]; then # Candidate path is relative, resolve to full path SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH fi done # Get final script directory path from fully resolved source path SCRIPT_DIR="$(cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd)" echo "$SCRIPT_DIR" } echo "get_script_dir: $(get_script_dir)"This last one will work with any combination of aliases,
source,bash -c, symlinks, etc.Beware: if you
cdto a different directory before running this snippet, the result may be incorrect!Also, watch out for
$CDPATHgotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when callingupdate_terminal_cwd >&2on Mac). Adding>/dev/null 2>&1at the end of yourcdcommand will take care of both possibilities.To understand how it works, try running this more verbose form:
#!/usr/bin/env bash SOURCE=${BASH_SOURCE[0]} while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE=$TARGET else DIR=$( dirname "$SOURCE" ) echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fi done echo "SOURCE is '$SOURCE'" RDIR=$( dirname "$SOURCE" ) DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd ) if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'" fi echo "DIR is '$DIR'"And it will print something like:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.') SOURCE is './sym2/scriptdir.sh' DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2' DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'From Stack Overflow: asked by Jiaaro, answered by dogbane (CC BY-SA 4.0)
How do I check if a directory exists or not in a Bash shell script?
To check if a directory exists:
if [ -d "$DIRECTORY" ]; then echo "$DIRECTORY does exist." fiTo check if a directory does not exist:
if [ ! -d "$DIRECTORY" ]; then echo "$DIRECTORY does not exist." fiHowever, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:
ln -s "$ACTUAL_DIR" "$SYMLINK" if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fiWill produce the error message:
rmdir: failed to remove `symlink': Not a directorySo symbolic links may have to be treated differently, if subsequent commands expect directories:
if [ -d "$LINK_OR_DIR" ]; then if [ -L "$LINK_OR_DIR" ]; then # It is a symlink! # Symbolic link specific commands go here. rm "$LINK_OR_DIR" else # It's a directory! # Directory command goes here. rmdir "$LINK_OR_DIR" fi fiTake particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean in another answer.
If the variables contain spaces or other unusual characters it will probably cause the script to fail.
From Stack Overflow: asked by Grundlefleck, answered by Grundlefleck (CC BY-SA 4.0)
How do I tell if a file does not exist in Bash?
The
testcommand (written as[here) has a "not" logical operator,!(exclamation mark):if [ ! -f /tmp/foo.txt ]; then echo "File not found!" fiFrom Stack Overflow: asked by Bill the Lizard, answered by John Feminella (CC BY-SA 4.0)
Echo newline in Bash prints literal \n
Use
printfinstead:printf 'Hello, \nWorld!\n'printfbehaves more consistently across different environments thanecho.From Stack Overflow: asked by Sergey, answered by sth (CC BY-SA 4.0)
How to check if a string contains a substring in Bash?
You can use Marcus's answer (* wildcards) outside a case statement, too, if you use double brackets:
string='My long string' if [[ $string == *"My long"* ]]; then echo "It's there!" fiNote that spaces in the needle string need to be placed between double quotes, and the
*wildcards should be outside. Also note that a simple comparison operator is used (i.e.==), not the regex operator=~.From Stack Overflow: asked by davidsheldon, answered by Adam Bellaire (CC BY-SA 4.0)
How to concatenate string variables in Bash?
foo="Hello" foo="${foo} World" echo "${foo}" > Hello WorldIn general to concatenate two variables you can just write them one after another:
a='Hello' b='World' c="${a} ${b}" echo "${c}" > Hello WorldFrom Stack Overflow: asked by Strawberry, answered by codaddict (CC BY-SA 4.0)
How can I check if a program exists from a Bash script?
Answer
POSIX compatible:
command -v <the_command>Example use:
if ! command -v <the_command> >/dev/null 2>&1 then echo "<the_command> could not be found" exit 1 fiFor Bash specific environments:
hash <the_command> # For regular commands. Or... type <the_command> # To check built-ins and keywordsExplanation
Avoid
which. Not only is it an external process you're launching for doing very little (meaning builtins likehash,typeorcommandare way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.Why care?
- Many operating systems have a
whichthat doesn't even set an exit status, meaning theif which foowon't even work there and will always report thatfooexists, even if it doesn't (note that some POSIX shells appear to do this forhashtoo). - Many operating systems make
whichdo custom and evil stuff like change the output or even hook into the package manager.
So, don't use
which. Instead use one of these:command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }(Minor side-note: some will suggest
2>&-is the same2>/dev/nullbut shorter – this is untrue.2>&-closes FD 2 which causes an error in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))
(Additional minor side-note: some will suggest&>/dev/null, but this is not POSIX compliant)If your hash bang is
/bin/shthen you should care about what POSIX says.typeandhash's exit codes aren't terribly well defined by POSIX, andhashis seen to exit successfully when the command doesn't exist (haven't seen this withtypeyet).command's exit status is well defined by POSIX, so that one is probably the safest to use.If your script uses
bashthough, POSIX rules don't really matter anymore and bothtypeandhashbecome perfectly safe to use.typenow has a-Pto search just thePATHandhashhas the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.As a simple example, here's a function that runs
gdateif it exists, otherwisedate:gnudate() { if hash gdate 2>/dev/null; then gdate "$@" else date "$@" fi }From Stack Overflow: asked by gregh, answered by lhunath (CC BY-SA 4.0)
- Many operating systems have a
How do I split a string on a delimiter in Bash?
You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to
IFSonly takes place to that single command's environment (toread). It then parses the input according to theIFSvariable value into an array, which we can then iterate over.This example will parse one line of items separated by
;, pushing it into an array:IFS=';' read -ra ADDR <<< "$IN" for i in "${ADDR[@]}"; do # process "$i" doneThis other example is for processing the whole content of
$IN, each time one line of input separated by;:while IFS=';' read -ra ADDR; do for i in "${ADDR[@]}"; do # process "$i" done done <<< "$IN"From Stack Overflow: asked by stefanB, answered by Johannes Schaub - litb (CC BY-SA 4.0)
Extract filename and extension in Bash
First, get file name without the path:
filename=$(basename -- "$fullfile") extension="${filename##*.}" filename="${filename%.*}"Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:
filename="${fullfile##*/}"You may want to check the documentation :
- On the web at section "3.5.3 Shell Parameter Expansion"
- In the bash manpage at section called "Parameter Expansion"
From Stack Overflow: asked by ibz, answered by Anya Shenanigans (CC BY-SA 4.0)
How to change the output color of echo in Linux?
You can use these ANSI escape codes:
Black 0;30 Dark Gray 1;30 Red 0;31 Light Red 1;31 Green 0;32 Light Green 1;32 Brown/Orange 0;33 Yellow 1;33 Blue 0;34 Light Blue 1;34 Purple 0;35 Light Purple 1;35 Cyan 0;36 Light Cyan 1;36 Light Gray 0;37 White 1;37And then use them like this in your script:
# .---------- constant part! # vvvv vvvv-- the code from above RED='\033[0;31m' NC='\033[0m' # No Color printf "I ${RED}love${NC} Stack Overflow\n"which prints
lovein red.From @james-lim's comment, if you are using the
echocommand, be sure to use the-eflag to allow backslash escapes.# .---------- constant part! # vvvv vvvv-- the code from above RED='\033[0;31m' NC='\033[0m' # No Color echo -e "I ${RED}love${NC} Stack Overflow"Note: Don't add
"\n"when usingechounless you want to add an additional empty line.From Stack Overflow: asked by satheesh.droid, answered by Tobias (CC BY-SA 4.0)
How do I parse command line arguments in Bash?
Bash Space-Separated (e.g.,
--option argument)cat >/tmp/demo-space-separated.sh <<'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION="$2" shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH="$2" shift # past argument shift # past value ;; --default) DEFAULT=YES shift # past argument ;; -*|--*) echo "Unknown option $1" exit 1 ;; *) POSITIONAL_ARGS+=("$1") # save positional arg shift # past argument ;; esac done set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 "$1" fi EOF chmod +x /tmp/demo-space-separated.sh /tmp/demo-space-separated.sh -e conf -s /etc /etc/hostsOutput from copy-pasting the block above
FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.comUsage
demo-space-separated.sh -e conf -s /etc /etc/hostsBash Equals-Separated (e.g.,
--option=argument)cat >/tmp/demo-equals-separated.sh <<'EOF' #!/bin/bash for i in "$@"; do case $i in -e=*|--extension=*) EXTENSION="${i#*=}" shift # past argument=value ;; -s=*|--searchpath=*) SEARCHPATH="${i#*=}" shift # past argument=value ;; --default) DEFAULT=YES shift # past argument with no value ;; -*|--*) echo "Unknown option $i" exit 1 ;; *) ;; esac done echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 $1 fi EOF chmod +x /tmp/demo-equals-separated.sh /tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hostsOutput from copy-pasting the block above
FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.comUsage
demo-equals-separated.sh -e=conf -s=/etc /etc/hostsTo better understand
${i#*=}search for "Substring Removal" in this guide. It is functionally equivalent to`sed 's/[^=]*=//' <<< "$i"`which calls a needless subprocess or`echo "$i" | sed 's/[^=]*=//'`which calls two needless subprocesses.Using bash with getopt[s]
getopt(1) limitations (older, relatively-recent
getoptversions):- can't handle arguments that are empty strings
- can't handle arguments with embedded whitespace
More recent
getoptversions don't have these limitations. For more information, see these docs.POSIX getopts
Additionally, the POSIX shell and others offer
getoptswhich doen't have these limitations. I've included a simplisticgetoptsexample.Read the rest at the sourceFrom Stack Overflow: asked by Redwood, answered by Bruno Bronosky (CC BY-SA 4.0)
How to check if a variable is set?
(Usually) The right way
if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fiwhere
${var+x}is a parameter expansion which evaluates to nothing ifvaris unset, and substitutes the stringxotherwise.Quotes Digression
Quotes can be omitted (so we can say
${var+x}instead of"${var+x}") because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands tox(which contains no word breaks so it needs no quotes), or to nothing (which results in[ -z ], which conveniently evaluates to the same value (true) that[ -z "" ]does as well)).However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to the first author of this quotes explanation who is also a major Bash coder), it would sometimes be better to write the solution with quotes as
[ -z "${var+x}" ], at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.(Often) The wrong way
if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fiThis is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if
var='', then the above solution will output "var is blank".The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.
The distinction may not be essential in every scenario though. In those cases
[ -z "$var" ]will be just fine.From Stack Overflow: asked by prosseek, answered by Lionel (CC BY-SA 4.0)
Why is it better to use "#!/usr/bin/env NAME" instead of "#!/path/to/NAME" as my shebang?
It isn't necessarily better.
The advantage of
#!/usr/bin/env pythonis that it will use whateverpythonexecutable appears first in the user's$PATH.The disadvantage of
#!/usr/bin/env pythonis that it will use whateverpythonexecutable appears first in the user's$PATH.That means that the script could behave differently depending on who runs it. For one user, it might use the
/usr/bin/pythonthat was installed with the OS. For another, it might use an experimental/home/phred/bin/pythonthat doesn't quite work correctly.And if
pythonis only installed in/usr/local/bin, a user who doesn't have/usr/local/binin$PATHwon't even be able to run the script. (That's probably not too likely on modern systems, but it could easily happen for a more obscure interpreter.)By specifying
#!/usr/bin/pythonyou specify exactly which interpreter will be used to run the script on a particular system.Another potential problem is that on many systems, the
#!/usr/bin/envtrick doesn't let you pass arguments to the intrepreter (other than the name of the script, which is passed implicitly). This usually isn't an issue, but it can be. Many Perl scripts are written with#!/usr/bin/perl -w, butuse warnings;is the recommended replacement these days. Csh scripts should use#!/bin/csh -f-- but csh scripts are not recommended in the first place. But there could be other examples.UPDATE: the
envof FreeBSD has a-Soption (copied by GNU coreutilsenvin 8.30 with a--split-stringalias) that allows passing multiple arguments, so for example#!/usr/bin/env csh -fwill fail on systems whose shebang accepts only one argument after the interpreter, but#!/usr/bin/env -S csh -fwill work on those such as Linux where what's after the interpreter is bundled into one argument. Manyenvimplementations such asNetBSD's,busybox,toyboxstill don't support it so that won't help you write portable scripts.I have a number of Perl scripts in a personal source control system that I install when I set up an account on a new system. I use an installer script that modifies the
#!line of each script as it installs it in my$HOME/bin. (I haven't had to use anything other than#!/usr/bin/perllately; it goes back to times when Perl often wasn't installed by default.)A minor point: the
#!/usr/bin/envtrick is arguably an abuse of theenvcommand, which was originally intended (as the name implies) to invoke a command with an altered environment. Furthermore, some older systems (including SunOS 4, if I recall correctly) didn't have theenvcommand in/usr/bin. Neither of these is likely to be a significant concern.envdoes work this way, a lot of scripts do use the#!/usr/bin/envtrick, and OS providers aren't likely to do anything to break it. It might be an issue if you want your script to run on a really old system, but then you're likely to need to modify it anyway.Another possible issue, (thanks to Sopalajo de Arrierez for pointing it out in comments) is that cron jobs run with a restricted environment. In particular,
$PATHis typically something like/usr/bin:/bin. So if the directory containing the interpreter doesn't happen to be in one of those directories, even if it's in your default$PATHin a user shell, then the/usr/bin/envtrick isn't going to work. You can specify the exact path, or you can add a line to your crontab to set$PATH(man 5 crontabfor details).Read the rest at the sourceFrom Unix & Linux Stack Exchange: asked by TheGeeko61, answered by Keith Thompson (CC BY-SA 4.0)
Using "${a:-b}" for variable assignment in scripts
This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable.
excerpt
${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.NOTE: This form also works,
${parameter-word}. According to the Bash documentation, for all such expansions:Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.
If you'd like to see a full list of all forms of parameter expansion available within Bash then I highly suggest you take a look at this topic in the Bash Hacker's wiki titled: "Parameter expansion".
Examples
variable doesn't exist
$ echo "$VAR1" $ VAR1="${VAR1:-default value}" $ echo "$VAR1" default valuevariable exists
$ VAR1="has value" $ echo "$VAR1" has value $ VAR1="${VAR1:-default value}" $ echo "$VAR1" has valueThe same thing can be done by evaluating other variables, or running commands within the default value portion of the notation.
$ VAR2="has another value" $ echo "$VAR2" has another value $ echo "$VAR1" $ $ VAR1="${VAR1:-$VAR2}" $ echo "$VAR1" has another valueMore Examples
You can also use a slightly different notation where it's just
VARX=${VARX-<def. value>}.$ echo "${VAR1-0}" has another value $ echo "${VAR2-0}" has another value $ echo "${VAR3-0}" 0In the above
$VAR1&$VAR2were already defined with the string "has another value" but$VAR3was undefined, so the default value was used instead,0.Another Example
$ VARX="${VAR3-0}" $ echo "$VARX" 0Checking and assigning using
:=notationLastly I'll mention the handy operator,
:=. This will do a check and assign a value if the variable under test is empty or undefined.Example
Notice that
$VAR1is now set. The operator:=did the test and the assignment in a single operation.$ unset VAR1 $ echo "$VAR1" $ echo "${VAR1:=default}" default $ echo "$VAR1" defaultHowever if the value is set prior, then it's left alone.
$ VAR1="some value" $ echo "${VAR1:=default}" some value $ echo "$VAR1" some valueHandy Dandy Reference Table
Read the rest at the sourceFrom Unix & Linux Stack Exchange: asked by Justin Garrison, answered by slm (CC BY-SA 4.0)
In a bash script, using the conditional "or" in an "if" statement
If you want to say
ORuse double pipe (||).if [ "$fname" = "a.txt" ] || [ "$fname" = "c.txt" ](The original OP code using
|was simply piping the output of the left side to the right side, in the same way any ordinary pipe works.)After many years of comments and misunderstanding, allow me to clarify.
To do
ORyou use||.Whether you use
[or[[ortestor((all depends on what you need on a case by case basis. It's wrong to say that one of those is preferred in all cases. Sometimes[is right and[[is wrong. But that's not what the question was. OP asked why|didn't work. The answer is because it should be||instead.From Unix & Linux Stack Exchange: asked by Andrew, answered by bahamat (CC BY-SA 4.0)
How can I pass a command line argument into a shell script?
The shell command and any arguments to that command appear as numbered shell variables:
$0has the string value of the command itself, something likescript,./script,/home/user/bin/scriptor whatever. Any arguments appear as"$1","$2","$3"and so on. The count of arguments is in the shell variable"$#".Common ways of dealing with this involve shell commands
getoptsandshift.getoptsis a lot like the Cgetopt()library function.shiftmoves the value of$2to$1,$3to$2, and so on;$#gets decremented. Code ends up looking at the value of"$1", doing things using acase…esacto decide on an action, and then doing ashiftto move$1to the next argument. It only ever has to examine$1, and maybe$#.From Unix & Linux Stack Exchange: asked by Paul, answered by user732 (CC BY-SA 4.0)
How do I change the extension of multiple files?
Straight from Greg's Wiki:
# Rename all *.txt to *.text for file in *.txt; do mv -- "$file" "${file%.txt}.text" done*.txtis a globbing pattern, using*as a wildcard to match any string.*.txtmatches all filenames ending with '.txt'.--marks the end of the option list. This avoids issues with filenames starting with hyphens.${file%.txt}is a parameter expansion, replaced by the value of thefilevariable with.txtremoved from the end.Also see the entry on why you shouldn't parse
ls.If you have to use
basename, your syntax would be:for file in *.txt; do mv -- "$file" "$(basename -- "$file" .txt).text" doneFrom Unix & Linux Stack Exchange: asked by afbr1201, answered by jasonwryan (CC BY-SA 4.0)
In Bash, when to alias, when to script and when to write a function?
An alias should effectively not (in general) do more than change the default options of a command. It is nothing more than simple text replacement on the command name. It can't do anything with arguments but pass them to the command it actually runs. So if you simply need to add an argument at the front of a single command, an alias will work. Common examples are
# Make ls output in color by default. alias ls="ls --color=auto" # make mv ask before overwriting a file by default alias mv="mv -i"A function should be used when you need to do something more complex than an alias but that wouldn't be of use on its own. For example, take this answer on a question I asked about changing
grep's default behavior depending on whether it's in a pipeline:grep() { if [[ -t 1 ]]; then command grep -n "$@" else command grep "$@" fi }It's a perfect example of a function because it is too complex for an alias (requiring different defaults based on a condition), but it's not something you'll need in a non-interactive script.
If you get too many functions or functions too big, put them into separate files in a hidden directory, and source them in your
~/.bashrc:if [ -d ~/.bash_functions ]; then for file in ~/.bash_functions/*; do . "$file" done fiA script should stand on its own. It should have value as something that can be re-used, or used for more than one purpose.
From Unix & Linux Stack Exchange: asked by ixtmixilix, answered by Kevin (CC BY-SA 3.0)
What characters do I need to escape when using sed in a sh script?
There are two levels of interpretation here: the shell, and sed.
In the shell, everything between single quotes is interpreted literally, except for single quotes themselves. You can effectively have a single quote between single quotes by writing
'\''(close single quote, one literal single quote, open single quote).Sed uses basic regular expressions. In a BRE, in order to have them treated literally, the characters
$.*[\^need to be quoted by preceding them by a backslash, except inside character sets ([…]). Letters, digits and(){}+?|must not be quoted (you can get away with quoting some of these in some implementations). The sequences\(,\),\n, and in some implementations\{,\},\+,\?,\|and other backslash+alphanumerics have special meanings. You can get away with not quoting$^in some positions in some implementations.Furthermore, you need a backslash before
/if it is to appear in the regex outside of bracket expressions. You can choose an alternative character as the delimiter by writing, e.g.,s~/dir~/replacement~or\~/dir~p; you'll need a backslash before the delimiter if you want to include it in the BRE. If you choose a character that has a special meaning in a BRE and you want to include it literally, you'll need three backslashes; I do not recommend this, as it may behave differently in some implementations.In a nutshell, for
sed 's/…/…/':- Write the regex between single quotes.
- Use
'\''to end up with a single quote in the regex. - Put a backslash before
$.*/[\]^and only those characters (but not inside bracket expressions). (Technically you shouldn't put a backslash before]but I don't know of an implementation that treats]and\]differently outside of bracket expressions.) - Inside a bracket expression, for
-to be treated literally, make sure it is first or last ([abc-]or[-abc], not[a-bc]). - Inside a bracket expression, for
^to be treated literally, make sure it is not first (use[abc^], not[^abc]). - To include
]in the list of characters matched by a bracket expression, make it the first character (or first after^for a negated set):[]abc]or[^]abc](not[abc]]nor[abc\]]).
In the replacement text:
&and\need to be quoted by preceding them by a backslash, as do the delimiter (usually/) and newlines.\followed by a digit has a special meaning.\followed by a letter has a special meaning (special characters) in some implementations, and\followed by some other character means\corcdepending on the implementation.- With single quotes around the argument (
sed 's/…/…/'), use'\''to put a single quote in the replacement text.
If the regex or replacement text comes from a shell variable, remember that
- The regex is a BRE, not a literal string.
- In the regex, a newline needs to be expressed as
\n(which will never match unless you have othersedcode adding newline characters to the pattern space). But note that it won't work inside bracket expressions with somesedimplementations. - In the replacement text,
&,\and newlines need to be quoted. - The delimiter needs to be quoted (but not inside bracket expressions).
- Use double quotes for interpolation:
sed -e "s/$BRE/$REPL/".
From Unix & Linux Stack Exchange: asked by detly, answered by Gilles 'SO- stop being evil' (CC BY-SA 4.0)
How do I trim leading and trailing whitespace from each line of some output?
Use
awk '{$1=$1;print}'or even shorter:
awk '{$1=$1};1'Would trim leading and trailing space or tab characters1 and also squeeze sequences of tabs and spaces into a single space.
That works because when you assign something to any one field and then try to access the whole record (
$0, the thingprintprints by default),awkneeds to rebuild that record by joining all fields ($1, ...,$NF) withOFS(space by default).To also remove blank lines, change it to
awk 'NF{$1=$1;print}'(whereNFas a condition selects the records for which theNumber ofFields is non-zero). Do not doawk '$1=$1'as sometimes suggested as that would also remove lines whose first field is any representation of0supported byawk(0,00,-0e+12...)¹ and possibly other blank characters depending on the locale and the
awkimplementationFrom Unix & Linux Stack Exchange: asked by rubo77, answered by Stéphane Chazelas (CC BY-SA 4.0)
Why does my shell script choke on whitespace or other special characters?
Always use double quotes around variable substitutions and command substitutions:
"$foo","$(foo)"If you use
$foounquoted, your script will choke on input or parameters (or command output, with$(foo)) containing whitespace or\[*?.There, you can stop reading. Well, ok, here are a few more:
read— To read input line by line with thereadbuiltin, usewhile IFS= read -r line; do …
Plainreadtreats backslashes and whitespace specially.xargs— Avoidxargs. If you must usexargs, make thatxargs -0. Instead offind … | xargs, preferfind … -exec ….
xargstreats whitespace and the characters\"'specially.
This answer applies to Bourne/POSIX-style shells (
sh,ash,dash,bash,ksh,mksh,yash…). Zsh users should skip it and read the end of When is double-quoting necessary? instead. If you want the whole nitty-gritty, read the standard or your shell's manual.Note that the explanations below contains a few approximations (statements that are true in most conditions but can be affected by the surrounding context or by configuration).
Why do I need to write
"$foo"? What happens without the quotes?$foodoes not mean “take the value of the variablefoo”. It means something much more complex:- First, take the value of the variable.
- Field splitting: treat that value as a whitespace-separated list of fields, and build the resulting list. For example, if the variable contains
foo * bar then the result of this step is the 3-element listfoo,*,bar. - Filename generation: treat each field as a glob, i.e. as a wildcard pattern, and replace it by the list of file names that match this pattern. If the pattern doesn't match any files, it is left unmodified. In our example, this results in the list containing
foo, following by the list of files in the current directory, and finallybar. If the current directory is empty, the result isfoo,*,bar.
Note that the result is a list of strings. There are two contexts in shell syntax: list context and string context. Field splitting and filename generation only happen in list context, but that's most of the time. Double quotes delimit a string context: the whole double-quoted string is a single string, not to be split. (Exception:
"$@"to expand to the list of positional parameters, e.g."$@"is equivalent to"$1" "$2" "$3"if there are three positional parameters. See What is the difference between $* and $@?)The same happens to command substitution with
$(foo)or with`foo`. On a side note, don't use`foo`: its quoting rules are weird and non-portable, and all modern shells support$(foo)which is absolutely equivalent except for having intuitive quoting rules.The output of arithmetic substitution also undergoes the same expansions, but that isn't normally a concern as it only contains non-expandable characters (assuming
IFSdoesn't contain digits or-).See When is double-quoting necessary? for more details about the cases when you can leave out the quotes.
Read the rest at the sourceFrom Unix & Linux Stack Exchange: asked by Gilles 'SO- stop being evil', answered by Gilles 'SO- stop being evil' (CC BY-SA 4.0)
How can I get my external IP address in a shell script?
I'd recommend getting it directly from a DNS server.
Most of the other answers below all involve going over HTTP to a remote server. Some of them required parsing of the output, or relied on the User-Agent header to make the server respond in plain text. Those change quite frequently (go down, change their name, put up ads, might change output format etc.).
- The DNS response protocol is standardised (the format will stay compatible).
- Historically, DNS services (Akamai, Google Public DNS, OpenDNS, ..) tend to survive much longer and are more stable, more scalable, and generally more looked-after than whatever new hip whatismyip dot-com HTTP service is hot today.
- This method is inherently faster (be it only by a few milliseconds!).
Using
digwith an OpenDNS resolver:$ dig @resolver4.opendns.com myip.opendns.com +shortPerhaps alias it in your
bashrcso it's easy to remember# https://unix.stackexchange.com/a/81699/37512 alias wanip='dig @resolver4.opendns.com myip.opendns.com +short' alias wanip4='dig @resolver4.opendns.com myip.opendns.com +short -4' alias wanip6='dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short -6'Responds with a plain ip address:
$ wanip # wanip4, or wanip6 80.100.192.168 # or, 2606:4700:4700::1111How it works
The dig command.
(Abbreviated from https://ss64.com/bash/dig.html. You can read this anytime via
man dig):usage: dig [@global-dnsserver] [q-type] <hostname> <d-opt> [q-opt] q-type one of (A, ANY, AAAA, TXT, MX, ...). Default: A. d-opt ... +[no]short (Display nothing except short form of answer) ... q-opt one of: -4 (use IPv4 query transport only) -6 (use IPv6 query transport only) ...The
ANYquery type returns either an AAAA or an A record. To prefer IPv4 or IPv6 connection specifically, use the-4or-6options accordingly.To require the response be an IPv4 address, replace ANY with
A; for IPv6, replace it withAAAA. Note that it can only return the address used for the connection. For example, when connecting over IPv6, it cannot return the A address.Alternative servers
Various DNS providers offer this service, including OpenDNS, Akamai, and Google Public DNS:
# OpenDNS (since 2009) $ dig @resolver3.opendns.com myip.opendns.com +short $ dig @resolver4.opendns.com myip.opendns.com +short 80.100.192.168 # OpenDNS IPv6 $ dig @resolver1.ipv6-sandbox.opendns.com AAAA myip.opendns.com +short -6 2606:4700:4700::1111 # Akamai (since 2009) $ dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short 80.100.192.168 # Akamai approximate # NOTE: This returns only an approximate IP from your block, # but has the benefit of working even when behind private DNS proxies. $ dig +short TXT whoami.ds.akahelp.net "ip" "80.100.192.160" # Google (since 2010) # Supports IPv6 + IPv4, use -4 or -6 to force one. $ dig @ns1.google.com TXT o-o.myaddr.l.google.com +short "80.100.192.168"Example alias that specifically requests an IPv4 address:
# https://unix.stackexchange.com/a/81699/37512 alias wanip4='dig @resolver4.opendns.com myip.opendns.com +short -4' $ wanip4 80.100.192.168And for your IPv6 address:
# https://unix.stackexchange.com/a/81699/37512 alias wanip6='dig @ns1.google.com TXT o-o.myaddr.l.google.com +short -6' $ wanip6 "2606:4700:4700::1111"Troubleshooting
Read the rest at the sourceFrom Unix & Linux Stack Exchange: asked by Eugene Yarmash, answered by Timo Tijhof (CC BY-SA 4.0)
How create a temporary file in shell script?
tmpfile=$(mktemp /tmp/abc-script.XXXXXX) : ... rm "$tmpfile"You can make sure that a file is deleted when the scripts exits (including kills and crashes) by opening a file descriptor to the file and deleting it. The file keeps available (for the script; not really for other processes but
/proc/$PID/fd/$FDis a work-around) as long as the file descriptor is open. When it gets closed (which the kernel does automatically when the process exits) the filesystem deletes the file.# create temporary file tmpfile=$(mktemp /tmp/abc-script.XXXXXX) # create file descriptor 3 for writing to a temporary file so that # echo ... >&3 writes to that file exec 3>"$tmpfile" # create file descriptor 4 for reading from the same file so that # the file seek positions for reading and writing can be different exec 4<"$tmpfile" # delete temp file; the directory entry is deleted at once; the reference counter # of the inode is decremented only after the file descriptor has been closed. # The file content blocks are deallocated (this is the real deletion) when the # reference counter drops to zero. rm "$tmpfile" # your script continues : ... # example of writing to file descriptor echo foo >&3 # your script continues : ... # reading from that file descriptor head -n 1 <&4 # close the file descriptor (done automatically when script exits) # see section 2.7.6 of the POSIX definition of the Shell Command Language exec 3>&-From Unix & Linux Stack Exchange: asked by Bhuvanesh, answered by Hauke Laging (CC BY-SA 4.0)
What is the meaning of IFS=$'\n' in bash scripting?
IFSstands for "internal field separator". It is used by the shell to determine how to do word splitting, i. e. how to recognize word boundaries.Try this in a shell like bash (other shells may handle this differently, for example zsh):
mystring="foo:bar baz rab" for word in $mystring; do echo "Word: $word" doneThe default value for
IFSconsists of whitespace characters (to be precise: space, tab and newline). Each character can be a word boundary. So, with the default value ofIFS, the loop above will print:Word: foo:bar Word: baz Word: rabIn other words, the shell thinks that whitespace is a word boundary.
Now, try setting
IFS=:before executing the loop. This time, the result is:Word: foo Word: bar baz rabNow, the shell splits
mystringinto words as well -- but now, it only treats a colon as the word boundary.The first character of
IFSis special: It is used to delimit words in the output when using the special$*variable (example taken from the Advanced Bash Scripting Guide, where you can also find more information on special variables like that one):$ bash -c 'set w x y z; IFS=":-;"; echo "$*"' w:x:y:zCompare to:
$ bash -c 'set w x y z; IFS="-:;"; echo "$*"' w-x-y-zNote that in both examples, the shell will still treat all of the characters
:,-and;as word boundaries. The only thing that changes is the behaviour of$*.Another important thing to know is how so-called "IFS whitespace" is treated. Basically, as soon as
IFSincludes whitespace characters, leading and trailing whitespace is stripped from the string to be split before processing it and a sequence of consecutive whitespace characters delimits fields as well. However, this only applies to those whitespace characters which are actually present inIFS.For example, let's look at the string
"a:b:: c d "(trailing space and two space characters betweencandd).- With
IFS=:it would be split into four fields:"a","b",""(empty string) and" c d "(again, two spaces betweencandd). Note the leading and trailing whitespace in the last field. - With
IFS=' :', it would be split into five fields:"a","b",""(empty string),"c"and"d". No leading and trailing whitespace anywhere.
Note how multiple, consecutive whitespace characters delimit two fields in the second example, while multiple, consecutive colons don't (since they are not whitespace characters).
As for
IFS=$'\n', that is aksh93syntax also supported bybash,zsh,mkshand FreeBSDsh(with variations between all shells). Quoting the bash manpage:Words of the form $'string' are treated specially. The word expands to "string", with backslash-escaped characters replaced as specified by the ANSI C standard.
\nis the escape sequence for a newline, soIFSends up being set to a single newline character.From Unix & Linux Stack Exchange: asked by Abdul Al Hazred, answered by Tilman Blumenbach (CC BY-SA 3.0)
- With
How can I test if a variable is empty or contains only spaces?
First, note that the
-ztest is explicitly for:the length of string is zero
That is, a string containing only spaces should not be true under
-z, because it has a non-zero length.What you want is to remove the spaces from the variable using the pattern replacement parameter expansion:
[[ -z "${param// }" ]]This expands the
paramvariable and replaces all matches of the pattern(a single space) with nothing, so a string that has only spaces in it will be expanded to an empty string.The nitty-gritty of how that works is that
${var/pattern/string}replaces the first longest match ofpatternwithstring. Whenpatternstarts with/(as above) then it replaces all the matches. Because the replacement is empty, we can omit the final/and thestringvalue:${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. ... If string is null, matches of pattern are deleted and the / following pattern may be omitted.
After all that, we end up with
${param// }to delete all spaces.Note that though present in
ksh(where it originated),zshandbash, that syntax is not POSIX and should not be used inshscripts.From Unix & Linux Stack Exchange: asked by maihabunash, answered by Michael Homer (CC BY-SA 3.0)
redirecting to /dev/null
No, this will not prevent the script from crashing. If any errors occur in the
tarprocess (e.g.: permission denied, no such file or directory, ...) the script will still crash.This is because of using
> /dev/null 2>&1will redirect all your command output (bothstdoutandstderr) to/dev/null, meaning no outputs are printed to the terminal.By default:
stdin ==> fd 0 stdout ==> fd 1 stderr ==> fd 2In the script, you use
> /dev/nullcausing:stdin ==> fd 0 stdout ==> /dev/null stderr ==> fd 2And then
2>&1causing:stdin ==> fd 0 stdout ==> /dev/null stderr ==> stdoutFrom Unix & Linux Stack Exchange: asked by JohnMerlino, answered by cuonglm (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA16 questions
- Unix & Linux Stack Exchangeby its contributors, named on each answerCC BY-SA24 questions