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
72
votes
1 answer

Download file with url redirection

I can download a file by url but when I try it from bash I get a html page instead of a file. How to download file with url redirection (301 Moved Permanently) using curl, wget or something else? UPD Headers from the url request. curl -I…
edem
  • 3,222
  • 3
  • 19
  • 45
72
votes
5 answers

Exit code of variable assignment to command substitution in Bash

I am confused about what error code the command will return when executing a variable assignment plainly and with command substitution: a=$(false); echo $? It outputs 1, which let me think that variable assignment doesn't sweep or produce new error…
Reorx
  • 2,801
  • 2
  • 24
  • 29
72
votes
5 answers

Git Checkout Latest Tag

I'm writing a shell script and I'm looking to checkout the latest version of repo. Specifically I want to break this process apart into multiple steps. I want to save the repositories latest tag into a variable Print out Checking out version:…
BFTrick
  • 5,211
  • 6
  • 24
  • 28
72
votes
14 answers

How to get the PID of a process that is piped to another process in Bash?

I am trying to implement a simple log server in Bash. It should take a file as a parameter and serve it on a port with netcat. ( tail -f $1 & ) | nc -l -p 9977 But the problem is that when the netcat terminates, tail is left behind running.…
Ertuğ Karamatlı
  • 898
  • 1
  • 6
  • 7
72
votes
8 answers

How to count number of words from String using shell

I want to count number of words from a String using Shell. Suppose the String is: input="Count from this String" Here the delimiter is space ' ' and expected output is 4. There can also be trailing space characters in the input string like "Count…
Yogesh Ralebhat
  • 1,376
  • 1
  • 13
  • 29
72
votes
15 answers

ZSH not recognizing my aliases?

Using iTerm2 with zsh and it isn't recognizing my aliases. Sometimes I have to work in an IDE and can't just easily vim something and the stupid people thought it a good idea to name their applications like MyReallyLongApplicationName.app and since…
o_O
  • 5,527
  • 12
  • 52
  • 90
72
votes
5 answers

Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?

Anyone know this? I've never been able to find an answer.
Kenneth Reitz
  • 8,559
  • 4
  • 31
  • 34
72
votes
5 answers

Using `date` command to get previous, current and next month

I am using below to get previous, current and the next month under Ubuntu 11.04: LAST_MONTH=`date +'%m' -d 'last month'` NEXT_MONTH=`date +'%m' -d 'next month'` THIS_MONTH=`date +'%m' -d 'now'` It works well until today, the last day of October,…
greeness
  • 15,956
  • 5
  • 50
  • 80
71
votes
8 answers

How to create md5 hash in bash in Mac OS X

How can you create an md5 hash for a string on a mac using bash? md5sum does not exist in my environment. I did a man for md5 but I'm confused about what that really does. md5 "string" does not return a hash.
WildBill
  • 9,143
  • 15
  • 63
  • 87
71
votes
6 answers

rm fails to delete files by wildcard from a script, but works from a shell prompt

I've run into a really silly problem with a Linux shell script. I want to delete all files with the extension ".bz2" in a directory. In the script I call rm "$archivedir/*.bz2" where $archivedir is a directory path. Should be pretty simple,…
EMP
  • 59,148
  • 53
  • 164
  • 220
71
votes
12 answers

Bash or KornShell (ksh)?

I am not new to *nix, however lately I have been spending a lot of time at the prompt. My question is what are the advantages of using KornShell (ksh) or Bash Shell? Where are the pitfalls of using one over the other? Looking to understand from the…
user13158
  • 721
  • 1
  • 6
  • 4
71
votes
6 answers

xargs doesn't recognize bash aliases

I'm trying to run the following command: find . -iname '.#*' -print0 | xargs -0 -L 1 foobar where "foobar" is an alias or function defined in my .bashrc file (in my case, it's a function that takes one parameter). Apparently xargs doesn't…
Ian Greenleaf Young
  • 1,888
  • 2
  • 15
  • 23
71
votes
10 answers

How to parse XML using shellscript?

I would like to know what would be the best way to parse an XML file using shellscript ? Should one do it by hand ? Does third tiers library exist ? If you already made it if you could let me know how did you manage to do it
Spredzy
  • 4,982
  • 13
  • 53
  • 69
71
votes
9 answers

shell replace cr\lf by comma

I have input.txt 1 2 3 4 5 I need to get such output.txt 1,2,3,4,5 How to do it?
vinnitu
  • 4,234
  • 10
  • 41
  • 59
71
votes
5 answers

Example of using named pipes in Linux shell (Bash)

Can someone post a simple example of using named pipes in Bash on Linux?
Drew LeSueur
  • 19,185
  • 29
  • 89
  • 106
1 2 3
99
100