[bash] 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했지만 출력이 올바르지 않습니다 (수동으로 명령을 실행하면 정상적으로 작동하므로 아무런 문제가 없습니다). 이를 수행하는 올바른 방법은 무엇입니까?

추신 : 물론 펄에서 모든 일을 할 수는 있지만 다른 상황에서 도움이 될 수 있기 때문에이 방법을 배우려고합니다.



답변

당신은 단지해야합니다 :

#!/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

대신 파일로.

이 예제에서는 특수 변수 ${RANDOM}(여기에서 학습 한 내용)를 사용하여 / etc / password 파일을 사용했습니다. sed차이점은 변수 확장을 허용하기 위해 단일 대신 큰 따옴표를 사용한다는 것입니다.


답변

경우에 당신은, 당신이해야 할 명령은 단지 하나의 문자열을 실행하고 아니에요을 인수를 포함한 여러 변수가 어디에 되지 는 다음과 같은 경우 실패로 평가 직접 사용합니다 :

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

“일부 인수”가 단일 인수로 전달 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() {
  "$@";
}

evaleval_command기능 의 출력 과 새 기능 의 차이점에 유의하십시오 .

eval_command echo_arguments arg1 arg2 "Some arg"

결과:

Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:


답변