2014-12-10 2 views
1

현재 특정 변수를 코딩 한 bash 스크립트가 있는데, 인수를 전달하여 이러한 변수를 설정할 수 있기를 바랍니다.기본값을 사용하여 bash 스크립트에 변수 전달하기

간단한 예 :

    : 있도록이 스크립트를 편집 할 수있는 경우 궁금 오전 열심히 변수에 대한 값을 코딩 한 스크립트 example.sh data_namesrun_this

    #!/bin/bash 
    
    data_names=("apple_picking" "iris") 
    run_this="TRUE"  
    
    #remainder of script runs things using these hard coded variables 
    

    을 고려

  1. 실행할 때 인수를 전달하여 data_namesrun_this의 값을 설정할 수 있습니다. bash example.sh

  2. data_namesrun_this에 대한 인수가 스크립트에 전달되지 않은 경우 변수는 기본 (하드 코딩 된) 값을 가져야합니다.

+1

네, 가능 :

run_this=${1:-TRUE} IFS=',' read -a data_names <<< "${2:-apple_picking,iris}" 

가정 스크립트가 같이이라고합니다. 지금까지 무엇을 시도 했습니까? – Robert

답변

2

당신은 강력한 무언가를 원하는 경우 명확한 & 우아한, 당신은 getopts에 모습 run_this

튜토리얼 설정하기 위해 수행해야 http://wiki.bash-hackers.org/howto/getopts_tutorial 예 : http://mywiki.wooledge.org/BashFAQ/035

다음과 같이 생각합니다.

./script --run-this=true "apple_picking" "iris" 
+1

고맙습니다! 이것은 주어진 순서에서 입력 인수를 지정할 필요가 없기 때문에/여러 입력 인수를 처리 할 수 ​​있기 때문에 가장 좋은 옵션입니다. –

+0

물론 이것은 제안 된 솔루션의 목표입니다. HTH –

0

당신은 사용할 수 있습니다

#!/bin/bash 

# create a BASH array using passed arguments 
data_names=("[email protected]") 

# if array is empty assign hard coded values 
[[ ${#data_names[@]} -eq 0 ]] && data_names=("apple_picking" "iris") 

# print argument array or do something else 
printf "%s\n" "${data_names[@]}"; 
0

또 다른 옵션은 다음과 같이이다 :

./script.sh first_argument array,values,in,second,argument 
관련 문제