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
76
votes
10 answers

How can I append text to /etc/apt/sources.list from the command line?

I am new to linux, and just beginning to learn bash. I am using Ubuntu 9.04, and would like to add repositories to /etc/apt/sources.list from the command line. Basically, I would like to do this: sudo echo "[some repository]" >>…
Matthew
  • 28,056
  • 26
  • 104
  • 170
76
votes
11 answers

Retrieving multiple arguments for a single option using getopts in Bash

I need help with getopts. I created a Bash script which looks like this when run: $ foo.sh -i env -d directory -s subdirectory -f file It works correctly when handling one argument from each flag. But when I invoke several arguments from each flag…
vegasbrianc
  • 989
  • 1
  • 7
  • 11
76
votes
4 answers

How does Ctrl-C terminate a child process?

I am trying to understand how CTRL+C terminates a child but not a parent process. I see this behavior in some script shells like bash where you can start some long-running process and then terminate it by entering CTRL-C and the control returns to…
vitaut
  • 49,672
  • 25
  • 199
  • 336
76
votes
6 answers

How to detect 386, amd64, arm, or arm64 OS architecture via shell/bash

I'm looking for a POSIX shell/bash command to determine if the OS architecture is 386, amd64, arm, or arm64?
Justin
  • 42,716
  • 77
  • 201
  • 296
76
votes
16 answers

PS1 line with Git current branch and colors

Here is my current PS1: export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ ' How can I display the current branch in a different color?
cfischer
  • 24,452
  • 37
  • 131
  • 214
76
votes
4 answers

Ansible: How to chmod +x a file with Ansible?

What is the best way to chmod + x a file with ansible. Converting the following script to ansible format. mv /tmp/metadata.sh /usr/local/bin/meta.sh chmod +x /usr/local/bin/meta.sh This is what I have so far.. - name: move /tmp/metadata.sh to…
Atlantic0
  • 3,271
  • 5
  • 17
  • 24
76
votes
3 answers

bash if -a vs -e option

Both about -a and -e options in Bash documentation is said: -a file True if file exists. -e file True if file exists. Trying to get what the difference is I ran the following script: resin_dir=/Test/Resin_wheleph/Results if [ -e…
wheleph
  • 7,974
  • 7
  • 40
  • 57
76
votes
6 answers

Bash: Capture output of command run in background

I'm trying to write a bash script that will get the output of a command that runs in the background. Unfortunately I can't get it to work, the variable I assign the output to is empty - if I replace the assignment with an echo command everything…
rthur
  • 1,466
  • 1
  • 15
  • 15
76
votes
17 answers

Recreating PyCharm launcher in Ubuntu

I installed pycharm normally via bin/pycharm.sh, but the mistake I made was doing bash pycharm.sh while the pycharm directory has inside the Downloads folder. I later on moved the directory to /opt/Pycharm/. This is causing the once functioning…
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
76
votes
4 answers

Use awk to find average of a column

I'm attempting to find the average of the second column of data using awk for a class. This is my current code, with the framework my instructor provided: #!/bin/awk ### This script currently prints the total number of rows processed. ### You must…
Ben Zifkin
  • 892
  • 2
  • 8
  • 16
76
votes
3 answers

Why exit code 141 with grep -q?

Can someone explain why I get exit code 141 from the below? #!/usr/bin/bash set -o pipefail zfs list | grep tank echo a ${PIPESTATUS[@]} zfs list | grep -q tank echo b ${PIPESTATUS[@]} cat /etc/passwd | grep -q root echo c ${PIPESTATUS[@]} I…
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
76
votes
4 answers

Where do you keep your own scripts on OSX?

As I write my bash scripts for my OS X that do general things, I am wondering where is a good place to keep them. Is there a directory I can put them all in where they will be picked up automatically? Or should I create my own directory and then…
More Than Five
  • 9,959
  • 21
  • 77
  • 127
76
votes
6 answers

Bash get exit status of command when 'set -e' is active?

I generally have -e set in my Bash scripts, but occasionally I would like to run a command and get the return value. Without doing the set +e; some-command; res=$?; set -e dance, how can I do that?
David Wolever
  • 148,955
  • 89
  • 346
  • 502
76
votes
2 answers

How can I copy several binary files into one file on a Linux system?

I need to copy the content of a folder which contains binary files to one binary file in another directory. In Windows I can just use: copy file1 + file2 targetfile /B I couldn't find something similar for Linux (I saw an approach with cat, but…
Ahatius
  • 4,777
  • 11
  • 49
  • 79
75
votes
20 answers

Bash: Split string into character array

I have a string in a Bash shell script that I want to split into an array of characters, not based on a delimiter but just one character per array index. How can I do this? Ideally it would not use any external programs. Let me rephrase that. My…
n s
  • 1,361
  • 2
  • 12
  • 24