Questions tagged [bash]

This tag is for questions about scripts written for the Bash command shell. For shell scripts with syntax or other errors, please check them at https://shellcheck.net before posting them here. Questions about the interactive use of Bash are more likely to be on-topic on Unix & Linux Stack Exchange or Super User than on Stack Overflow.

About Bash

There are a variety of interpreters that receive commands either interactively or as a sequence of commands from a file. The Bourne-again shell (Bash) is one such interpreter. Bash implements the standard Bourne Shell (sh), and offers numerous additions.

From the Free Software Foundation's Bash page:

Bash is an sh-compatible shell that incorporates useful features from the KornShell (ksh) and C shell (csh). It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard. It offers functional improvements over sh for both programming and interactive use. In addition, most sh scripts can be run by Bash without modification.

Read the Bash manual for technical details.

Bash was written by Brian Fox and first released in 1989. It is the default shell in many Linux distributions; it is available on most modern operating systems, and has been ported to Windows 10.

A note regarding versions

As of September 2022, the most recent version of bash is 5.2, although you may be using an older version depending on your operating system and which updates to bash have been installed. Most Linux installations should be using something in the 4.x family. macOS (formerly Mac OS X) only provides version 3.2 due to licensing issues.

Be sure to note in your question what version of bash you are using. This will alert potential answerers to what features are available to you, as well as which bugs may need to be worked around.

You can determine which version of bash you are using by running bash --version or checking the value of the BASH_VERSION shell variable.

Without an explicit version, an answerer may well assume you are using at least version 4.2 (it's been available for over 10 years). Questions tagged imply version 3.2 unless otherwise stated.

A Brief Release History

Based on downloads available from http://ftp.gnu.org/gnu/bash/

Version Release Date
3.2 2006-10-11
4.0 2009-02-20
4.1 2009-12-31
4.2 2011-02-13
4.3 2014-02-26
4.4 2016-09-15
5.0 2019-01-07
5.1 2020-12-06
5.2 2022-09-26

Additionally, all versions for bash from 2.0 and later received an important patch-level release to address the Shellshock vulnerability in September 2014.

Before asking about problematic code

To help the kind people who assist you, to ensure that future readers can benefit from your question, and to help ensure your question is voted up as useful for that lovely karma, please make your question as simple and universal as possible:

  1. Check whether your script or data has DOS style end-of-line characters

    • Use cat -v yourfile or echo "$yourvariable" | cat -v .

      DOS carriage returns will show up as ^M after each line.

      If you find them, delete them using dos2unix (a.k.a. fromdos) or tr -d '\r'

  2. Make sure you run the script with bash, not sh

    • The first line in the script must be #!/bin/bash or #!/usr/bin/env bash.

      It must not be #!/bin/sh even if your system's /bin/sh is a symlink to /bin/bash

    • Run the script with ./yourscript or bash yourscript.

      Do not run it with sh yourscript.

      This applies even when sh is a symlink to bash.

  3. Find a small, self-contained example.

    • Don't include sections and commands unrelated to your problem.
    • Avoid complex commands that just serve to produce a value (include the value directly).
    • Avoid relying on external files. Create the files on the fly, include the data directly, or post a small example of a file in your question.
  4. Test your example. Make sure it runs and still shows the problem. Do not brush this off.

    • Reformatting for clarity often sidesteps pitfalls related to spacing and naming.
    • Refactoring for simplicity often sidesteps pitfalls related to subshells.
    • Mocking out files and data often sidesteps problems related to special characters.
    • Hours spent trying multiple things often leads to posting code from one version and errors from another.
  5. Check the example for common problems

    • Run your example through shellcheck or the online ShellCheck service to automatically check for common mistakes.
    • Browse Bash pitfalls and Bash beginner's mistakes as well as the Popular Questions section below for checklists of common issues.
    • Check your data for special characters, using cat -v yourfile or cat -v <<< "$yourvar". Be especially careful with carriage returns (shown as ^M).
  6. Please avoid tagging questions that are solely about external commands. The bash tag should be reserved for Bash-related problems, not any CLI problem you might have.

How to turn a bad script into a good question

For example, let's say you have a script for alerting you when a server is idle, but it keeps alerting even when the machine is not idle:

# Avoid code like this when asking about a problem
# It has irrelevant code and external dependencies, and is hard to read and run

while true
do
  load=$(wget -O - "http://$1/load.php" | grep "^load:" | cut -d: -f 2)
  if [[ $load=="0" ]]
  then
    mailx -s "System is idle" user@example.com <<< "The server is idle"
    break
  else
    echo "Waiting..."
    sleep 60
  fi
done
  1. The problem still occurs without the loop: Remove the loop from your question.
  2. The problem still occurs if you skip asking the server: Hard code the response (e.g. load=42)
  3. The problem still occurs without emailing: Use echo "Why does this run?"
  4. The problem still occurs when removing the else branch. Shorten it

We're now left with this small, self-contained example:

# Prefer code like this when asking about a problem
# It's small, simple and self contained, making it easy to read and run.

load=42
if [[ $load=="0" ]]
then
  echo "Why does this run?"
fi

Thanks for making your question simple and useful! Enjoy your upvotes!

(However, note that this example is simple to compare against the relevant entry in Bash pitfalls and the error is automatically caught by shellcheck, so now you don't actually need to ask!)

Popular Questions

Some frequently asked Bash questions include the following.

Basic Syntax and Common Newbie Problems

Some fundamentals of Bash are surprising even to veterans from other programming languages.

How Do I ...?

Why Does ...?

Common Tasks

These questions are not really specific to Bash, but frequent enough in this tag that they deserve to be included here.

Meta

Books and Resources

Additional reading materials include:

Tools

  • shellcheck - a static analysis tool that detects common mistakes
  • on-line ShellCheck, a web server providing shellcheck (useful if you've not yet installed the program)
  • https://explainshell.com/ can pick apart many command lines and explain what the elements mean (notice that you can sometimes click on a result to have it picked apart further)

Chat

The Stack Overflow bash chat is useful for coordinating work within this tag, and perhaps occasionally for getting quick help (though no guarantees can be made; attendance is spotty).

154003 questions
1447
votes
7 answers

Passing parameters to a Bash function

I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line. I would like to pass parameters within my script. I tried: myBackupFunction("..", "...", "xx") function…
stivlo
  • 83,644
  • 31
  • 142
  • 199
1418
votes
27 answers

How can I declare and use Boolean variables in a shell script?

I tried to declare a Boolean variable in a shell script using the following syntax: variable=$false variable=$true Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using…
hassaanm
  • 14,539
  • 4
  • 21
  • 20
1388
votes
28 answers

How to count lines in a document?

I have lines like these, and I want to know how many lines I actually have... 09:16:39 AM all 2.00 0.00 4.00 0.00 0.00 0.00 0.00 0.00 94.00 09:16:40 AM all 5.00 0.00 0.00 4.00 0.00 0.00 0.00 0.00 …
Alucard
  • 16,628
  • 7
  • 24
  • 23
1381
votes
25 answers

How to escape single quotes within single quoted strings

Let's say, you have a Bash alias like: alias rxvt='urxvt' which works fine. However: alias rxvt='urxvt -fg '#111111' -bg '#111111'' won't work, and neither will: alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\'' So how do you end up matching up…
cons
  • 14,423
  • 4
  • 20
  • 14
1340
votes
17 answers

Replace one substring for another string in shell script

I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara". firstString="I love Suzi and Marry" secondString="Sara" Desired result: firstString="I love Sara and Marry"
Zincode
  • 13,441
  • 3
  • 13
  • 6
1309
votes
52 answers

How to trim whitespace from a Bash variable?

I have a shell script with this code: var=`hg st -R "$path"` if [ -n "$var" ]; then echo $var fi But the conditional code always executes, because hg st always prints at least one newline character. Is there a simple way to strip whitespace…
too much php
  • 88,666
  • 34
  • 128
  • 138
1283
votes
11 answers

Assigning default values to shell variables with a single command in bash

I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.: if [ -z "${VARIABLE}" ]; then FOO='default' else FOO=${VARIABLE} fi I seem to recall there's some…
Edward Q. Bridges
  • 16,712
  • 8
  • 35
  • 42
1278
votes
32 answers

Pipe to/from the clipboard in a Bash script

Is it possible to pipe to/from the clipboard in Bash? Whether it is piping to/from a device handle or using an auxiliary application, I can't find anything. For example, if /dev/clip was a device linking to the clipboard we could do: cat /dev/clip …
moinudin
  • 134,091
  • 45
  • 190
  • 216
1259
votes
29 answers

Listing only directories using ls in Bash?

This command lists directories in the current path: ls -d */ What exactly does the pattern */ do? And how can we give the absolute path in the above command (e.g. ls -d /home/alice/Documents) for listing only directories in that path?
Sibi
  • 47,472
  • 16
  • 95
  • 163
1254
votes
16 answers

How to echo shell commands as they are executed

In a shell script, how do I echo all shell commands called and expand any variable names? For example, given the following line: ls $DIRNAME I would like the script to run the command and display the following ls /full/path/to/some/dir The purpose…
Jack Nock
  • 14,703
  • 5
  • 22
  • 18
1247
votes
46 answers

Parsing JSON with Unix tools

I'm trying to parse JSON returned from a curl request, like so: curl 'http://twitter.com/users/username.json' | sed -e 's/[{}]/''/g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' The above splits the JSON into…
auser
  • 13,808
  • 4
  • 21
  • 15
1241
votes
11 answers

How can I pipe stderr, and not stdout?

I have a program that writes information to stdout and stderr, and I need to process the stderr with grep, leaving stdout aside. Using a temporary file, one could do it in two steps: command > /dev/null 2> temp.file grep 'something' temp.file But…
user80168
1216
votes
12 answers

How to compare strings in Bash

How do I compare a variable to a string (and do something if they match)?
Erik Sapir
  • 23,209
  • 28
  • 81
  • 141
1212
votes
12 answers

Propagate all arguments in a Bash shell script

I am writing a very simple script that calls another script, and I need to propagate the parameters from my current script to the script I am executing. For instance, my script name is foo.sh and calls bar.sh. foo.sh: bar $1 $2 $3 $4 How can I do…
Fragsworth
  • 33,919
  • 27
  • 84
  • 97
1210
votes
15 answers

How to reload .bash_profile from the command line

How can I reload file .bash_profile from the command line? I can get the shell to recognize changes to .bash_profile by exiting and logging back in, but I would like to be able to do it on demand.
markdorison
  • 139,374
  • 27
  • 55
  • 71