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

How to remove files starting with double hyphen?

I have some files on my Unix machine that start with -- e.g. --testings.html If I try to remove it I get the following error: cb0$ rm --testings.html rm: illegal option -- - usage: rm [-f | -i] [-dPRrvW] file ... unlink file I tried rm…
cb0
  • 8,415
  • 9
  • 52
  • 80
75
votes
4 answers

linux find regex

I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line. Why are these not the same? find -regex '.*[1234567890]' find -regex '.*[[:digit:]]' Bash, Ubuntu
Dijkstra
  • 2,490
  • 3
  • 21
  • 35
75
votes
2 answers

What's the meaning of a ! before a command in the shell?

What is the purpose of a shell command (part of a shell script) starting with an exclamation mark? Concrete example: In foo.sh: #!/usr/bin/env bash set -e ! docker stop foo ! docker rm -f foo # ... other stuff I know that without the space the…
sthzg
  • 5,514
  • 2
  • 29
  • 50
75
votes
3 answers

How to use multiline command in 'script:' with YAML?

I have a repository that uses Travis CI, and in the .travis.yml there I have this line: script: - vim -Nu <(cat <<-EOF set nocompatible | filetype off EOF ) -c 'Script' > /dev/null Sadly this doesn't work, as this is transformed into a…
hgiesel
  • 5,430
  • 2
  • 29
  • 56
75
votes
11 answers

Jenkins: Pipeline sh bad substitution error

A step in my pipeline uploads a .tar to an artifactory server. I am getting a Bad substitution error when passing in env.BUILD_NUMBER, but the same commands works when the number is hard coded. The script is written in groovy through jenkins and is…
Stephen Nichols
  • 2,363
  • 5
  • 14
  • 19
75
votes
2 answers

What is the difference between "$@" and "$*" in Bash?

It seems to me that they both store all the command-line arguments. So is there a difference between the two?
Debugger
  • 9,130
  • 17
  • 45
  • 53
75
votes
1 answer

System.getenv() returns null when the environment variable exists

I am trying to System.getenv() to get the value of an environment variable that I have set through my terminal (Mac), I also set the variable in my .bash_profile file and reloaded. After doing so, I echo'd the value and the correct value was printed…
SamTebbs33
  • 5,507
  • 3
  • 22
  • 44
75
votes
8 answers

Bash, grep between two lines with specified string

Example: a43 test1 abc cvb bnm test2 kfo I need all lines between test1 and test2. Normal grep does not work in this case. Do you have any propositions?
user3162968
  • 1,016
  • 1
  • 9
  • 16
75
votes
7 answers

File size in human readable format

Given the size of a file in bytes, I want to format it with IEC (binary) prefixes to 3 significant figures with trailing zeros, e.g. 1883954 becomes 1.80M. Floating-point arithmetic isn't supported in bash, so I used awk instead. The problem is I…
someguy
  • 7,144
  • 12
  • 43
  • 57
75
votes
4 answers

Run bash commands from txt file

I have some commands in txt file and I need to execute all them line by line. How could I do it?
Андрей
  • 873
  • 1
  • 7
  • 5
75
votes
5 answers

How to run a vim command from the shell command-line?

There are many stackoverflow questions about running shell programs from within vim. Is it is possible to do the reverse, i.e., $ vim :BundleInstall to allow me to run BundleInstall as part of a shell script, rather than having to open vim and run…
jvc26
  • 6,363
  • 6
  • 46
  • 75
75
votes
1 answer

Meaning of "=~" operator in shell script

I came across a shell script where the code is for line in $LIST_ARRAY;do if [[ $LIST_ARRAY =~ $line ]] then echo "true" .... ... . What is the use of =~ in this case?
cc4re
  • 4,821
  • 3
  • 20
  • 27
74
votes
8 answers

How to make a GUI for bash scripts?

I want to make some graphical dialogs for my script but don't know how. I hear something about GTK-Server or something like that. If someone knows how to link Bash with tcl/tk I also be satisfied. Please do not post something like "change to C++"…
lauriys
  • 4,652
  • 7
  • 32
  • 40
74
votes
6 answers

How to define a function inside another function in Bash?

I have the following code func1(){ #some function thing function2(){ #second function thing } } and I want to call function2 but I get an error function2 : not found Is there a solution?
tiranodev
  • 943
  • 2
  • 8
  • 15
74
votes
8 answers

Find file in directory from command line

In editors/ides such as eclipse and textmate, there are shortcuts to quickly find a particular file in a project directory. Is there a similar tool to do full path completion on filenames within a directory (recursively), in bash or other shell? I…
whoisbenli
  • 1,095
  • 1
  • 9
  • 12