How to Prompt for Argument If Not Provided in Command in Bash

The aim of this page📝 is to explain how command line arguments and user prompts work in shell scripts, based on the particular example of my script helping me to create a zettelkasten for VSCode in which I manage my tasks and knowledge.

Pavol Kutaj
2 min readJan 13, 2024
  • In the provided script, command substitution is used to replace the read and echo commands with the user's input.
make_z4v() {
# Parameters
kbType="${1:-$(read -p "Type(s/k): " name && echo "$name")}"
name="${2:-$(read -p "Name: " name && echo "$name")}"
extract="${3:-$(read -p "Extract: " extract && echo "$extract")}"
cat="${4:-$(read -p "Category: " cat && echo "$cat")}"
open="${5:-$(read -p "Open: " open && echo "$open")}"
url="${6:-$(read -p "URL: " url && echo "$url")}"

# Get current date
today=$(date +"%Y-%m-%d")
#...
  • Shell scripts can accept command-line arguments.
  • These arguments are accessible inside the script using special variables ($1, $2, etc.).
  • The variable $1 refers to the first argument, $2 to the second, and so on.
  • In the provided script, several variables (kbType, name, extract, cat, open, URL) are being set based on these arguments.
  • If an argument is not provided, the script prompts the user for input.
  • This is done using the read command, which reads a line from standard input.
  • The -p option allows a prompt string to be specified.
  • The entered input is stored in a variable.
  • The && operator is used to chain commands together.
  • The echo command is used to print the value of the variable.
  • The :- operator provides a default value for a variable if it is unset or null.
  • This operator is part of parameter expansion in shell scripts.
  • Command substitution ($(command)) is used to replace a command with its output.
  • Compare that to Powershell from which I am currently switching to bash
function New-Kba {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$kbType,
[Parameter(Mandatory = $true)][string]$name,
[Parameter(Mandatory = $true)][string]$cat,
[Parameter(Mandatory = $true)][bool]$open?,
[Parameter(Mandatory = $true)]$url,
[Parameter(Mandatory = $true)]$extract
)

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com