简体   繁体   中英

Expand variable in the bash script to pass its value in the single quotes

I have written following shell script:

#!/bin/bash

for ff in $(ls *.mkv *.mp4 *.avi); do
    echo Processing $ff
    php -r 'echo ph_dct_videohash("$ff");' 
done

But instead of expected substitution of $ff with its current value in the php line I am getting error: PHP Notice: Undefined variable: ff in Command line code on line 1 . Looks like $ff have been passed as is but not as its expansion. How can I achieve to pass expansion of ff instead of $ff ?

Try this: 'echo ph_dct_videohash("'$ff'");' .

( '$ff' is literally $ff , but "$ff" and $ff expand to the value of the variable ff ).

Update. A more correct approach (for names with whitespaces):

for ff in *.mkv *.mp4 *.avi; do
    echo "Processing $ff"
    php -r 'echo ph_dct_videohash("'"$ff"'");'
done

'echo ph_dct_videohash("'"$ff"'");' will always expand to one argument for php , and adding $ characters to the PHP code would not cause additional shell variable expansion (because of '...' ).

You aren't passing a variable; you are attempting to dynamically construct a PHP command, which has all sorts of problems and security risks.

To actually pass a value to PHP as a argument, use something like

for ff in *.mkv *.mp4 *.avi; do
    echo "Processing $ff"
    php -r 'echo ph_dct_videohash($argv[1]);' "$ff"
done

(My knowledge of PHP itself is a bit lacking; you many need to adjust my PHP code, but the call to php should be correct.)

just undo the quotes just before the $ff evaluation and resume them afterwards, like this:

php -r 'echo ph_dct_videohash("'$ff'");'

This won't work as-is if the filenames contain spaces. Other answers have addressed the "don't use output of ls " by using directly wildcards in for . I won't paraphrase those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM