Create a function invoked as backup archive.tar.gz source-dir.
Pass the first and second arguments to tar -czf.
Which definition is appropriate?
A Bash function uses NAME() { commands; }; $1 and $2 refer to its call arguments and should be quoted.
Detailed explanation
backup() { tar -czf "$1" "$2"; }Correct. The function passes the first and second call arguments to tar.
Correct. The function passes the first and second call arguments to tar.
backup() { tar -czf "$0" "$1"; }Incorrect. $0 is normally the shell or script name, not the first function argument.
Incorrect. $0 is normally the shell or script name, not the first function argument.
alias backup='tar -czf $1 $2'Incorrect. An alias does not provide function-style positional parameters.
Incorrect. An alias does not provide function-style positional parameters.
backup { tar -czf "$1" "$2" }Incorrect. The required function syntax and command terminator are missing.
Incorrect. The required function syntax and command terminator are missing.
Try it yourself
An example you can run in a temporary verification environment.
bash --noprofile --norc -c 'backup(){ printf "out=%s src=%s\n" "$1" "$2"; }; backup archive.tar.gz source-dir'Expected result
out=archive.tar.gz src=source-dirKey points
- NAME() { ...; }
- $1 is first argument
- Quote positional parameters
Notes
- Environment: GNU Bash 5.2 / 一時関数
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.