나는 어떻게 전달할 수 있는 것은 무엇인가 하는 검색 기능, 배시 매개변수입니다 들려온다 항상 전달하는 방법을 매개변수입니다 &solarisdvd 명령줄입니다.
I would like to pass 매개변수입니다 내 스크립트입니다. 내가 시도했다.
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
하지만, 내 함수은 매개변수입니다 정확하지 않은 구문은 통과하는 방법?
두 가지 일반적인 방법 선언할 수 있다. 나는 두 번째 방법을 선호한다.
function function_name {
command...
}
또는
function_name () {
command...
}
함수 호출 인수와 함께:
function_name "$arg1" "$arg2"
전달 함수 () 은 그들의 포지셔닝하십시오 인수를 아닌 이름으로), 즉 1 달러, $2) 등이 있습니다. $0을 이름은 스크립트입니다 할 수 있다.
예:
function_name () {
echo "Parameter #1 is $1"
}
또한 함수은 문의 후 하는 것은 없다.
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
<! - 언어: > 랑 없음 -;
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
지식이 높은 수준의 프로그래밍 언어 (C/C++/Java/PHP/Python/Perl.) 레이먼 노력해야 할 수 있는 기능을 할 수 있는 것처럼 제시할 것이라고 배시 '로 끝난다. 총괄하였습니다 같이 일하는 것이 아니라, 배시 셸을 명령 및 작성되지는 인수만 전달될 수 있는 옵션을 전달하십시오 같은 방법으로 그들을 한 권능은하나님께 셸 명령 (ls - l). 실제로 bash 인수만 함수은 취급됩니다 위치 매개변수 ('$1, $2. $9, 10$ {}}, {11$' 등). 이는 '어떻게' 제포츠 작동됨 고려할 때 당연한 일입니다. 괄호는 bash 함수 호출 할 필요는 없다.
( 참고 : 내가 지금 무슨 일이 일어날 수 있는 오픈 solris apc®.)
# bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - $1 | zip -n .jpg:.gif:.png $2 - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - $1 | zip -n .jpg:.gif:.png $2 - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
#In the actual shell script
#$0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
내가 이 방법을 개발한 release. 매개변수입니다 전달된 다음과 같은 함수를 정의할 수 있습니다
function example { args : string firstName , string lastName , integer age } {
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}
@Required 또는 @readonly 만드시겠습니까 오레스트 인수만 만드시겠습니까 어레이에는 인수만 주석을 달 수도 있습니다) 으로 충스러웠으니 순차인지 인수 (예를 들어 '사용하는 문자열 [4]') 와 선택적으로 인수만 나열하십시오 여러 선:
function example {
args
: @required string firstName
: string lastName
: integer age
: string[] ...favoriteHobbies
echo "My name is ${firstName} ${lastName} and I am ${age} years old."
echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}
즉, 해당 이름으로 매개변수입니다 아니라 고객의 문의할 수 있습니다 (읽을 수 있는 보다 구성하는 핵심), 실제로 전달하십시오 어레이에는 수 있습니다 (그리고 이 기능을 사용할 수 있습니다 - 4.3 표시되어도 변수에 대한 참조가 bash)! 또한 매핑되었습니다 변수는 모두 로컬 유효범위 마찬가지로 1 달러 (등).
이번 작품은 모두 할 수 있는 코드를 아주 가볍고 작동됨 bash 3 과 4 배쉬 (이 두 가지뿐입니다 I& # 39, ve 테스트되었습니다 버전 또한). # 39 더 관심이 있는 경우, re you& 개발을 통해 이 같은 훨씬 더 쉽고, 배시 괜찮게 만드는 요령을 보면 내 취할 수 있는 Bash 인피니티 레임워크 중 하나로, 아래 코드는 해당 기능을 사용할 수 있습니다.
shopt -s expand_aliases
function assignTrap {
local evalString
local -i paramIndex=${__paramIndex-0}
local initialCommand="${1-}"
if [[ "$initialCommand" != ":" ]]
then
echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
return
fi
while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
do
shift # first colon ":" or next parameter's comma ","
paramIndex+=1
local -a decorators=()
while [[ "${1-}" == "@"* ]]
do
decorators+=( "$1" )
shift
done
local declaration=
local wrapLeft='"'
local wrapRight='"'
local nextType="$1"
local length=1
case ${nextType} in
string | boolean) declaration="local " ;;
integer) declaration="local -i" ;;
reference) declaration="local -n" ;;
arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
"string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
"integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
esac
if [[ "${declaration}" != "" ]]
then
shift
local nextName="$1"
for decorator in "${decorators[@]}"
do
case ${decorator} in
@readonly) declaration+="r" ;;
@required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
@global) declaration+="g" ;;
esac
done
local paramRange="$paramIndex"
if [[ -z "$length" ]]
then
# ...rest
paramRange="{@:$paramIndex}"
# trim leading ...
nextName="${nextName//\./}"
if [[ "${#@}" -gt 1 ]]
then
echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
fi
elif [[ "$length" -gt 1 ]]
then
paramRange="{@:$paramIndex:$length}"
paramIndex+=$((length - 1))
fi
evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "
# continue to the next param:
shift
fi
done
echo "${evalString} local -i __paramIndex=${paramIndex};"
}
alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'
이 예에서는 도와주겠어 좋겠다 그 두 개의 숫자를 걸리는 사용자로부터 급지됩니다 함수에 대한 추가 불렀으매 ',' (in the very last line of the code) 및 '숨' 은 그 추가 설치 및 인쇄 저들이요
#!/bin/bash
read -p "Enter the first value: " x
read -p "Enter the second value: " y
add(){
arg1=$1 #arg1 gets to be the first assigned argument (note there are no spaces)
arg2=$2 #arg2 gets to be the second assigned argument (note there are no spaces)
echo $(($arg1 + $arg2))
}
add x y #feeding the arguments
#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}
declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );
myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];
4.3 은 bash 대체 구문을 사용하여 [남레프] [1]
비록 남레프 는 훨씬 더 편리하게 사용할 수 있다는 점에서 여전히 일부 완벽하게 역참조 tfsnap 출하됩니다 배포판은 ui_policytable_java_spe_policy 이전 버전 # 39, 그래서 won& 추천합니까 아직 꽤 된다.
[1]: http://wiki.bash-hackers.org/commands/builtin/declare # 남레프
간단한 예를 실행할 수 있는 동안 모두 선택해제합니다 스크립트입니다 함수를 호출할 때 또는 내부 스크립트입니다.
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" #as string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) #process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" #space sparted value
#you can also pass paramter durign executing script
print_param_value "$1" "$2" #parameter $1 and $2 during executing
#suppose our script name is param_example
# call like this
# ./param_example 5 5
# now the param will be $1=5 and $2=5