Repeated shell logic becomes easier to change when one named command owns it. A Bash function groups commands behind a callable name, receives arguments through positional parameters, and reports success or failure through its return status.
Arguments supplied to a function temporarily become $1, $2, and the remaining positional parameters while that function runs. Declaring a working variable with local keeps it from replacing a same-named variable in the surrounding script.
A regular-file check exposes both outcomes without external services or privileged setup. An existing file produces status 0, while a missing path produces status 1 that the caller can handle or pass back to the shell.
Related: How to create and run a Bash script
Related: How to use conditionals in Bash scripts
Related: How to source a function file in Bash
#!/usr/bin/env bash set -u describe_path() { local path=$1 }
The braces contain the function body. The local declaration copies the first function argument without changing a same-named variable outside the function.
if [[ -f $path ]]; then printf 'regular file: %s\n' "$path" return 0 fi
return 0 stops the function with a successful status as soon as path names a regular file.
printf 'not a regular file: %s\n' "$path" >&2 return 1
The diagnostic goes to standard error, and return 1 gives the caller a nonzero status it can test.
describe_path "${1:?Usage: bash function-demo.sh PATH}"
The :? expansion stops the script with the usage message when no path argument is supplied. Because the function call is the script's final command, its return value also becomes the script's exit status.
#!/usr/bin/env bash set -u describe_path() { local path=$1 if [[ -f $path ]]; then printf 'regular file: %s\n' "$path" return 0 fi printf 'not a regular file: %s\n' "$path" >&2 return 1 } describe_path "${1:?Usage: bash function-demo.sh PATH}"
$ bash -n function-demo.sh
No output means Bash parsed the file without finding a syntax error; it does not exercise either return path.
$ bash function-demo.sh function-demo.sh regular file: function-demo.sh
$ bash function-demo.sh missing.txt not a regular file: missing.txt
$ printf 'exit_status=%d\n' "$?" exit_status=1
Status 1 confirms that the function's failure value reached the calling shell.