Bash 스크립트 - 실행할 명령어로서의 가변 콘텐츠
파일 행에 대응하는 정의된 난수 목록을 제공하는 Perl 스크립트가 있습니다.그런 다음 다음 다음 명령을 사용하여 파일에서 해당 행을 추출합니다.sed
.
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var=$(perl test.pl test2 $count)
변수var
다음과 같은 출력을 반환합니다.cat last_queries.txt | sed -n '12p;500p;700p'
문제는 이 마지막 명령을 실행할 수 없다는 것입니다.로 시도했다.$var
출력은 올바르지 않습니다(명령어를 수동으로 실행하면 정상적으로 동작하므로 문제 없습니다).올바른 방법은 무엇입니까?
추신: 물론 Perl에서 모든 작업을 수행할 수 있지만, 다른 상황에서 도움이 될 수 있기 때문에 이 방법을 배우려고 합니다.
다음 작업만 하면 됩니다.
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)
단, Perl 명령어를 나중에 호출하여 변수에 할당하는 경우에는 다음과 같이 하십시오.
#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
...stuff...
eval $var
Bash의 도움:
~$ help eval
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
당신은 아마 당신이 원하는 것은eval $var
.
line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd
파일만 있으면 됩니다.
이 예에서는 특수 변수를 사용하여 /etc/password 파일을 사용했습니다.${RANDOM}
(여기서 배운 것)그리고sed
다른 점은 변수 확장을 허용하기 위해 단일 따옴표 대신 이중 따옴표를 사용한다는 것입니다.
셸 스크립트에서 문자열 명령을 실행하는 방법은 파라미터로 지정되었는지 여부에 관계없이 기본적으로 두 가지가 있습니다.
COMMAND="ls -lah"
$(echo $COMMAND)
또는
COMMAND="ls -lah"
bash -c $COMMAND
단일 문자열이 아니라 실행 중인 명령어의 인수를 포함하는 변수가 여러 개 있는 경우 eval을 직접 사용하지 마십시오.이 경우 다음과 같은 경우 실패합니다.
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
결과:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
"Some arg"는 단일 인수로 전달되었지만eval
둘로 읽습니다.
대신 명령어 자체로서 스트링을 사용할 수 있습니다.
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
출력의 차이에 주의해 주세요.eval
및 새로운eval_command
기능:
eval_command echo_arguments arg1 arg2 "Some arg"
결과:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
더 나은 방법
기능 사용:
# define it
myls() {
ls -l "/tmp/test/my dir"
}
# run it
myls
배열 사용:
# define the array
mycmd=(ls -l "/tmp/test/my dir")
# run the command
"${mycmd[@]}"
cmd="ls -atr ${HOME} | tail -1" <br/>
echo "$cmd" <br/>
VAR_FIRST_FILE=$( eval "${cmd}" ) <br/>
또는
cmd=("ls -atr ${HOME} | tail -1") <br/>
echo "$cmd" <br/>
VAR_FIRST_FILE=$( eval "${cmd[@]}" )
언급URL : https://stackoverflow.com/questions/5998066/bash-script-variable-content-as-a-command-to-run
'programing' 카테고리의 다른 글
클래스가 NSObjectProtocol을 준수하지 않습니다. (0) | 2023.04.13 |
---|---|
sed를 사용하여 파일의 마지막 n 행을 삭제하는 방법 (0) | 2023.04.13 |
Python에서 사전 목록 검색 (0) | 2023.04.13 |
이 시스템에서 스크립트 실행이 사용되지 않도록 설정되었기 때문에 .ps1을 로드할 수 없습니다. (0) | 2023.04.13 |
Excel 정규 분포를 사용하여 난수 생성 (0) | 2023.04.13 |