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
79
votes
16 answers

Extract parameters before last parameter in "$@"

I'm trying to create a Bash script that will extract the last parameter given from the command line into a variable to be used elsewhere. Here's the script I'm working on: #!/bin/bash # compact - archive and compact file/folder(s) eval…
user148813
  • 885
  • 1
  • 7
  • 11
79
votes
5 answers

"git add" using wildcard is not functioning as I hoped - must I cd into specific directories?

When I try to do a basic git add *.erb (or any simple wildcard expressions) git is not recognizing it (them). As a side-note, I have never done this before so I'm sure it's a rookie mistake, but I've found no help in other SO posts or my school's…
RudyOnRails
  • 1,819
  • 3
  • 17
  • 26
78
votes
9 answers

Always include first line in grep

I often grep CSV files with column names on the first line. Therefore, I want the output of grep to always include the first line (to get the column names) as well as any lines matching the grep pattern. What is the best way to do this?
jhourback
  • 4,381
  • 4
  • 26
  • 31
78
votes
3 answers

grep only text files

find . -type f | xargs file | grep text | cut -d':' -f1 | xargs grep -l "TEXTSEARCH" {} it's a good solution? for find TEXTSEARCH recursively in only textual files
stefcud
  • 2,220
  • 4
  • 27
  • 37
78
votes
11 answers

List files not matching a pattern?

Here's how one might list all files matching a pattern in bash: ls *.jar How to list the complement of a pattern? i.e. all files not matching *.jar?
calebds
  • 25,670
  • 9
  • 46
  • 74
78
votes
17 answers

Correct way to check Java version from BASH script

How can I check whether Java is available (in the PATH or via JAVA_HOME) from a bash script and make sure the version is at least 1.5?
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
78
votes
2 answers

Remove function definition (unalias equivalent)

I'm currently building a program which adds to the current user's shell depending on the project he's working on, by defining per-project aliases and functions. These aliases and functions may and will certainly have the same name like for instance…
greg0ire
  • 22,714
  • 16
  • 72
  • 101
78
votes
18 answers

Is there any use for Bash scripting anymore?

I just finished my second year as a university CS student, so my "real-world" knowledge is lacking. I learned Java my first year, continued with Java and picked up C and simple Bash scripting my second. This summer I'm trying to learn Perl (God…
Daniel Harms
  • 1,178
  • 1
  • 11
  • 20
78
votes
6 answers

How do I copy cookies from Chrome?

I am using bash to to POST to a website that requires that I be logged in first. So I need to send the request with login cookie. So I tried logging in and keeping the cookies, but it doesn't work because the site uses javascript to hash the…
jackcogdill
  • 4,900
  • 3
  • 30
  • 48
78
votes
7 answers

How to read mutliline input from stdin into variable and how to print one out in shell(sh,bash)?

What I want to do is the following: read in multiple line input from stdin into variable A make various operations on A pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command The current problem is that, I can't read it in with…
kakas
78
votes
4 answers

What is the meaning of the ${0##...} syntax with variable, braces and hash character in bash?

I just saw some code in bash that I didn't quite understand. Being the newbie bash scripter, I'm not sure what's going on. echo ${0##/*} echo ${0} I don't really see a difference in output in these two commands (prints the script name). Is that…
user215997
  • 1,267
  • 2
  • 12
  • 12
78
votes
3 answers

How can I redirect all output to /dev/null?

I want to run a program (google-chrome) in the background, but prevent it from outputting any messages to the terminal. I tried doing this: google-chrome 2>&1 1>/dev/null & However, the terminal still fills up without messages…
Benubird
  • 18,551
  • 27
  • 90
  • 141
78
votes
3 answers

How to pipe multiple commands into a single command in the shell? (sh, bash, ...)

How can I pipe the stdout of multiple commands to a single command? Example 1: combine and sort the output of all three echo commands: echo zzz; echo aaa; echo kkk desired output: aaa kkk zzz Example 2: rewrite the following so that all the…
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
78
votes
14 answers

How do I add ~/bin to my path?

I've been having trouble modifying my path to add Sublime Text 2. I've added a ~/bin directory and run this command: ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/subl The subl link appears in ~/bin. But I need to…
Graeme
  • 1,107
  • 2
  • 10
  • 11
77
votes
9 answers

"CLS" Equivalent in BASH?

How do you clear the entire terminal in BASH, like the command prompt's cls command? clear doesn't work because it doesn't actually clear anything, it just scrolls down.
user541686
  • 205,094
  • 128
  • 528
  • 886