pass a variable

2017-11-22  本文已影响3人  9b559869875b

https://developer.apple.com/library/content/documentation/OpenSource/Conceptual/ShellScripting/shell_scripts/shell_scripts.html

Of course, this script isn’t particularly useful. It just prints the words “Hello, world!“ to your screen. To make this more interesting, the next script throws in a few variables.

#!/bin/sh

FIRST_ARGUMENT="$1"

echo "Hello, world $FIRST_ARGUMENT!"

Type or paste this script into the text editor of your choice (see Creating Text Files in Your Home Directory for help creating a text file) and save the file in your home directory in a file called test.sh.

Once you have saved the file in your home directory, type ‘chmod a+x test.sh’ in Terminal to make it executable. Finally, run it with ‘./test.sh leaders’. You should see “Hello, world leaders!” printed to your screen.

This script provides an example of a variable assignment. The variable $1 contains the first argument passed to the shell script. In this example, the script makes a copy and stores it into a variable called FIRST_ARGUMENT, then prints that variable.

You should immediately notice that variables may or may not begin with a dollar sign, depending on how you are using them. If you want to dereference a variable, you precede it with a dollar sign. The shell then inserts the contents of the variable at that point in the script. For all other uses, you do not precede it with a dollar sign.

上一篇 下一篇

猜你喜欢

热点阅读