The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

If you can read me, I'm broken!

Views: 148,937β€…    Votes:  17β€…
Tag : bash  
Link: πŸ” See Original Answer on Ask Ubuntu ⧉ πŸ”—

URL: https://askubuntu.com/q/939627
Title: What does $# mean in bash?
ID: /2017/07/25/What-does-__-mean-in-bash_
Created: July 25, 2017    Edited:  February 11, 2022
Upload: April 8, 2024    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false


$# is typically used in bash scripts to ensure a parameter is passed. Generally, you check for a parameter at the beginning of your script.

For example, here’s a snippet of a script I was working on today:

if [[ $# -ne 1 ]]; then
    echo 'One argument required for the file name, e.g. "Backup-2017-07-25"'
    echo '.tar will automatically be added as a file extension'
    exit 1
fi

To summarize $# reports the number of parameters passed to a script. In your case, you passed no parameters and the reported result is 0.


Other # uses in Bash

The # is often used in bash to count the number of occurrences or the length of a variable.

To find the length of a string:

myvar="some string"; echo ${#myvar}

returns: 11

To find the number of array elements:

myArr=(A B C); echo ${#myArr[@]}

returns: 3

To find the length of the first array element:

myArr=(A B C); echo ${#myArr[0]}

returns: 1 (The length of A, 0 is the first element as arrays use zero-based indices/subscripts).

⇧ What is the difference between /etc/profile and .bashrc 16.04 - Network Menu gone and clicking Connect does nothing  β‡©