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
83
votes
7 answers

running multiple bash commands with subprocess

If I run echo a; echo b in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole of the rest of the line. The code below echos a; echo b instead of a b, how do I get it…
Paul
  • 5,756
  • 6
  • 48
  • 78
83
votes
5 answers

When setting IFS to split on newlines, why is it necessary to include a backspace?

I'm curious as to why the backspace is necessary when setting IFS to split on newlines like this: IFS=$(echo -en "\n\b") Why can I not just use this (which doesn't work) instead? IFS=$(echo -en "\n") I'm on a Linux system that is saving files with…
user431931
  • 855
  • 1
  • 6
  • 7
83
votes
4 answers

How to get the nth positional argument in bash?

How to get the nth positional argument in Bash, where n is variable?
hcs42
  • 13,376
  • 6
  • 41
  • 36
83
votes
8 answers

Is there a way to avoid positional arguments in bash?

I have to write a function in bash. The function will take about 7 arguments. I know that I can call a function like this: To call a function with parameters: function_name $arg1 $arg2 And I can refer my parameters like this inside the…
Bhushan
  • 18,329
  • 31
  • 104
  • 137
82
votes
4 answers

How to use Bash read with a timeout?

I can ask the user to press Enter by using read, and have him wait by calling sleep. But I can’t think of a way of doing both at the same time. I would like the user to be given the choice: Press Ctrl+C to Cancel, Enter to continue or just wait…
qdii
  • 12,505
  • 10
  • 59
  • 116
82
votes
6 answers

diff a directory recursively, ignoring all binary files

Working on a Fedora Constantine box. I am looking to diff two directories recursively to check for source changes. Due to the setup of the project (prior to my own engagement with said project! sigh), the directories contain both source and…
Zéychin
  • 4,135
  • 2
  • 28
  • 27
82
votes
6 answers

How do I use a pipe in the exec parameter for a find command?

I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, -exec on find doesn't allow to use pipe or even \| because the shell interprets that character first. Here is…
hoyhoy
  • 6,281
  • 7
  • 38
  • 36
82
votes
13 answers

Exporting an array in bash script

I can not export an array from a bash script to another bash script like this: export myArray[0]="Hello" export myArray[1]="World" When I write like this there are no problem: export myArray=("Hello" "World") For several reasons I need to…
Remiii
  • 1,102
  • 1
  • 8
  • 12
82
votes
4 answers

Kubernetes: how to debug CrashLoopBackOff

I have the following setup: A docker image omg/telperion on docker hub A kubernetes cluster (with 4 nodes, each with ~50GB RAM) and plenty resources I followed tutorials to pull images from dockerhub to…
ixaxaar
  • 6,411
  • 3
  • 24
  • 33
82
votes
3 answers

Run a shell script and immediately background it, however keep the ability to inspect its output

How can I run a shell script and immediately background it, however keep the ability to inspect its output any time by tailing /tmp/output.txt. It would be nice if I can foreground the process too later. P.S. It would be really cool if you can also…
82
votes
3 answers

Which shell I am using in mac

Default shell in my mac was bash. I have tried to change it into ZSH by command chsh -s /bin/zsh. Now when I am trying to check the shell type, I am getting different responses. COMMAND-1 input : echo $SHELL output : /bin/zsh COMMAND-2 input : ps…
shantanu
  • 1,748
  • 3
  • 19
  • 34
82
votes
4 answers

Sed gives: sed: can't read : No such file or directory

I have the following bash script which repeats for each image found. It needs to iterated over all html, css and js files, and replace all occurrences of an image within that file. for image in app/www/images-theme-dark/*.png do echo…
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
82
votes
8 answers

Shell script to open a URL

How do I write a simple shell script (say script.sh), so that I can pass a URL as an argument while executing? I want a browser to start with the page opened on that URL. I want to write the command in the script to open a browser and open the URL…
darecoder
  • 1,478
  • 2
  • 14
  • 29
82
votes
1 answer

.bash_profile sed: \1 not defined in the RE

I've to set up a local web development environment on my OS X 10.9 and installed Homebrew. Next step in my guide tells me to add logic to my ~/.bash_profile with the following command: echo "export PATH=\$(echo \$PATH | sed 's|/usr/local/bin||;…
leymannx
  • 5,138
  • 5
  • 45
  • 48
82
votes
8 answers

How to make OS X to read .bash_profile not .profile file

I have read so many suggestions about, not putting your customization aka commands in ".profile" file. Rather, create a .bash_profile for yourself and add your alias and etc. But,when I open the new terminal, if there is only .bash_profile, OS X is…
cherryhitech
  • 2,089
  • 3
  • 17
  • 15