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

Command line arguments in Bash

I want to write a bash script which takes different arguments. It should be used like normal linux console programs: my_bash_script -p 2 -l 5 -t 20 So the value 2 should be saved in a variable called pages and the parameter l should be saved in a…
Pascal
  • 2,175
  • 4
  • 39
  • 57
81
votes
8 answers

Are there any languages that compile to Bash?

I both love and hate writing Bash. I love that it's so streamlined for operating on files and working with processes (I agree with this popular question that it's way better in this regard than Python, Ruby, etc.), but I hate the syntax,…
Aseem Kishore
  • 10,404
  • 10
  • 51
  • 56
80
votes
12 answers

Fastest possible grep

I'd like to know if there is any tip to make grep as fast as possible. I have a rather large base of text files to search in the quickest possible way. I've made them all lowercase, so that I could get rid of -i option. This makes the search much…
pistacchio
  • 56,889
  • 107
  • 278
  • 420
80
votes
3 answers

Can I use sed to manipulate a variable in bash?

In my program, I would like to first get the user input, and insert a \ before each / so I write this, but it doesn't work. echo "input a website" read website sed '/\//i\/' $website
Leo Chan
  • 4,217
  • 8
  • 31
  • 47
80
votes
5 answers

Bash scripts with tmux to launch a 4-paned window

Can anyone help explain what's going on with tmux, bash, and exec? I'm trying to set up a tmux session with a 4-pane window. Ideally, I want to run a command in 3 of the panes: e.g. a Ruby Thin server and a couple of Ruby daemons. This is what I…
Aaron Gibralter
  • 4,773
  • 3
  • 35
  • 50
80
votes
8 answers

OpenVPN on Linux: passing username and password in command line

I am using IPVanish for using a proxy while surfing; like: sudo openvpn --config /home/ipv/conf/ipvanish-CA-Toronto-tor-a09.ovpn Now, I have to enter my username, after that my password. How Can I pass those two params right as one command, so that…
JOhnlw009a
  • 1,012
  • 1
  • 7
  • 12
80
votes
4 answers

How to trap ERR when using 'set -e' in Bash

I have a simple script : #!/bin/bash set -e trap "echo BOO!" ERR function func(){ ls /root/ } func I would like to trap ERR if my script fails (as it will here b/c I do not have the permissions to look into /root). However, when using set…
irritable_phd_syndrome
  • 4,631
  • 3
  • 32
  • 60
80
votes
1 answer

Which shortcut in Zsh does the same as Ctrl-U in Bash?

In Bash, when I am typing a command, I press Ctrl+U, all characters from the beginning of the line to the cursor are going to be removed. However, in zsh, if I pressed Ctrl+U, the whole line is gone. How to do the same in Zsh as in Bash?
Kent
  • 189,393
  • 32
  • 233
  • 301
80
votes
1 answer

What does the colon dash ":-" mean in bash

The result is the one desired; after a bit of trial and error. I don't understand what the "2:-" and "3:-" do/mean. Can someone explain. #!/bin/bash pid=$(ps -ef | grep java | awk ' NR ==1 {print $2}') count=${2:-30} # defaults to 30…
Stelios
  • 1,294
  • 3
  • 12
  • 28
80
votes
6 answers

Listing the content of a tar file or a directory only down to some level

I wonder how to list the content of a tar file only down to some level? I understand tar tvf mytar.tar will list all files, but sometimes I would like to only see directories down to some level. Similarly, for the command ls, how do I control the…
Tim
  • 1
  • 141
  • 372
  • 590
80
votes
9 answers

Delete all broken symbolic links with a line?

For a given folder, how can I delete all broken links within it? I found this answer that shows how to delete one broken link, but I can't put that together in only one line. Is there a one-liner for this? A broken symbolic is a link that points to …
fotanus
  • 19,618
  • 13
  • 77
  • 111
80
votes
4 answers

How do you print received cookie info to stdout with curl?

How do you print received cookie info to stdout with curl? According to the man pages if you use '-' as the file name for the -c --cookie-jar option it should print the cookie to stdout. The problem is I get an error: curl: option -: is…
Brian Yeh
  • 3,119
  • 3
  • 26
  • 40
80
votes
9 answers

Home/End keys do not work in tmux

I'm currently using tmux with xterm-256color $TERM variable. When in bash under tmux, pressing home/end would insert tilde characters (~). Outside of tmux the home/end keys work fine. Using cat and tput, I could see that there was a mismatch…
Ben Davis
  • 13,112
  • 10
  • 50
  • 65
80
votes
5 answers

Repeat last command with "sudo"

I often forget to run commands with sudo. I'm looking for a way to make a bash function (or alias) for repeating the last command with sudo. Something like: S() { sudo $(history 1) } Any ideas?
clt60
  • 62,119
  • 17
  • 107
  • 194
80
votes
2 answers

Use of apostrophe (single-quote) in a Git commit message via command line

I am trying to take this one step further. How could this work in a standard Bash shell? git commit -m 'cracked enigma's code' Could this simply be done with backslash-escaping like the following? git commit -m 'cracked enigma\'s code' Further,…
nutty about natty
  • 1,267
  • 2
  • 10
  • 17