2016-03-15 12 views
6

Jestem bardzo nowy w skryptach Bash, czy ktoś może mi wyjaśnić, w jaki sposób $ # i $? działa w następujący kod?

#!/bin/bash 

ARGS=3   # Script requires 3 arguments. 
E_BADARGS=85 # Wrong number of arguments passed to script. 

if [ $# -ne "$ARGS" ] 
then 
    echo "Usage: `basename $0` old-pattern new-pattern filename" 
    exit $E_BADARGS 
fi 

old_pattern=$1 
new_pattern=$2 

if [ -f "$3" ] 
then 
    file_name=$3 
else 
    echo "File \"$3\" does not exist." 
    exit $E_BADARGS 
fi 

exit $? 

Odpowiedz

11

Od Learn Bash in Y minutes:

# Builtin variables: 
# There are some useful builtin variables, like 
echo "Last program's return value: $?" 
echo "Script's PID: $$" 
echo "Number of arguments passed to script: $#" 
echo "All arguments passed to script: [email protected]" 
echo "Script's arguments separated into different variables: $1 $2..." 
1

$# pokazuje liczbę argumentów skryptu $? pokazuje wartość zwracana ostatniego skryptu

o argumentach: echo "ARG[$#]" przed if a następnie uruchomić skrypt jak

script.sh 1 

ouput będzie

ARG[1] 
Usage: g old-pattern new-pattern filename 

i tak dalej

ouput $? mogą być wykorzystane także w wierszu poleceń:

#shell>ls 
file1.txt  g    inpu    nodes_list 
#shell>echo $? 
0 

#shell>ls FileNameNotFound 
ls: FileNameNotFound: No such file or directory 
#shell> echo $? 
1 
Powiązane problemy