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
74
votes
2 answers

Convert line endings

I have been using d2u to convert line endings. After installing Puppy Linux I noticed that it does not come with d2u, but dos2unix. Then I noticed that Ubuntu is missing both by default. What is another way to convert line endings?
Zombo
  • 1
  • 62
  • 391
  • 407
74
votes
14 answers

How to convert hex to ASCII characters in the Linux shell?

Let's say that I have a string 5a. This is the hex representation of the ASCII letter Z. I need to find a Linux shell command which will take a hex string and output the ASCII characters that the hex string represents. So if I do: echo 5a |…
Krystian Cybulski
  • 10,789
  • 12
  • 67
  • 98
74
votes
4 answers

Deleting files after adding to tar archive

Can GNU tar add many files to an archive, deleting each one as it is added? This is useful when there is not enough disk space to hold both the entire tar archive and the original files - and therefore it is not possible to simply manually delete…
Ivy
  • 3,393
  • 11
  • 33
  • 46
74
votes
8 answers

Is it possible to detect 32 bit vs 64 bit in a bash script?

I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct…
Mike Stone
  • 44,224
  • 30
  • 113
  • 140
73
votes
11 answers

How do you run a script on login in *nix?

I know I once know how to do this but... how do you run a script (bash is OK) on login in unix?
Nate
  • 18,892
  • 27
  • 70
  • 93
73
votes
12 answers

How to suppress Terminated message after killing in bash?

How can you suppress the Terminated message that comes up after you kill a process in a bash script? I tried set +bm, but that doesn't work. I know another solution involves calling exec 2> /dev/null, but is that reliable? How do I reset it back so…
user14437
  • 3,130
  • 5
  • 21
  • 13
73
votes
7 answers

Convert date formats in bash

I have a date in this format: "27 JUN 2011" and I want to convert it to 20110627 Is it possible to do in bash?
vehomzzz
  • 42,832
  • 72
  • 186
  • 216
73
votes
7 answers

How can I format the output of a bash command in neat columns

I have a function which outputs many rows of information which I want to format in columns. The problem is that the width of any particular "cell" (if I may use that term) of data is variable, so piping it to something like awk does not give me…
iconoclast
  • 21,213
  • 15
  • 102
  • 138
73
votes
2 answers

Why does "local" discard the return code of a command?

This Bash snippet works as expected: $ fun1() { x=$(false); echo "exit code: $?"; } $ fun1 exit code: 1 But this one, using local, does not as I would have expected: $ fun2() { local x=$(false); echo "exit code: $?"; } $ fun2 exit code: 0 Can…
tokland
  • 66,169
  • 13
  • 144
  • 170
73
votes
4 answers

Using `find -perm` to find when a permission is not set

I want to find the non-readable files in my directory (eg the files with g-r). So I tried this: find . -perm -g-r It shows me all of the files?? So I tried this: find . -perm -g+r And it showed me only the readable files. It appears that -perm…
User1
  • 39,458
  • 69
  • 187
  • 265
73
votes
3 answers

How do I use a regex in a shell script?

I want to match an input string (contained in the variable $1) with a regex representing the date formats MM/DD/YYYY and MM-DD-YYYY. REGEX_DATE="^\d{2}[\/\-]\d{2}[\/\-]\d{4}$"   echo "$1" | grep -q $REGEX_DATE echo $? The echo $? returns the error…
Jérôme G
  • 968
  • 2
  • 7
  • 14
73
votes
2 answers

How do I change my $PS1 on a Macbook for oh-my-zsh?

I'm trying to find the PS1 variable in oh-my-zsh and change it so iTerm doesn't look as clogged up. Running the following command: echo $PS1 gives me this %{%f%b%k%}$(build_prompt) Additionally, I've attempted to edit the .zshrc file and…
Daniel Dao
  • 830
  • 1
  • 7
  • 11
73
votes
11 answers

Round a divided number in Bash

How would I round the result from two divided numbers, e.g. 3/2 As when I do testOne=$((3/2)) $testOne contains "1" when it should have rounded up to "2" as the answer from 3/2=1.5
Mint
  • 14,388
  • 30
  • 76
  • 108
73
votes
2 answers

Boolean operators ( &&, -a, ||, -o ) in Bash

What is the difference between the &&, ||, -a, and -o Unix operators? What are the restrictions on the usage of both types? Is it simply that the && and || operators should be used when using flags in the condition? As in: [ "$1" = "yes" ] && [ -r…
Victor Brunell
  • 5,668
  • 10
  • 30
  • 46
73
votes
11 answers

How can I upload (FTP) files to server in a Bash script?

I'm trying to write a Bash script that uploads a file to a server. How can I achieve this? Is a Bash script the right thing to use for this?
Andrew
  • 227,796
  • 193
  • 515
  • 708