简体   繁体   中英

bash| assign arguments to variables while escaping spaces

This is bash script which prints framerate of a video and the argument it takes may contain spaces. also this argument is going to be used in a command inside the script.

#!/bin/bash
inputVid="$*"

#checking if $inputVid has full path 
echo $inputVid

frames=`ffmpeg -i $inputVid 2>&1 | sed -n "s/.*, \(.*\) fp.*/\1/p"`
echo $frames

when I execute

$./frameRate.sh ../Downloads/FlareGet/Videos/Why\ .mp4 

output is:

../Downloads/FlareGet/Videos/Why .mp4

so the filename is getting passed correctly but spaces are not getting escaped hence no output from ffmpeg

is there any way to solve this ?

If your command only takes one argument, use $1 . All you need to do is properly quote both the original argument and the parameter $1 inside your script.

# Equivalent invocations
$ ./frameRate.sh ../Downloads/FlareGet/Videos/Why\ .mp4
$ ./frameRate.sh ../Downloads/FlareGet/Videos/"Why .mp4"
$ ./frameRate.sh "../Downloads/FlareGet/Videos/Why .mp4"

The script would be

inputVid="$1"
ffmpeg -i "$inputVid" 2>&1 | sed -n "s/.*, \(.*\) fp.*/\1/p"

or simply

ffmpeg -i "$1" 2>&1 | sed -n "s/.*, \(.*\) fp.*/\1/p"

If this does't work, then your Python script is not passing the argument correctly, and there is isn't really anything you can do to accommodate it.

In addition to using double quotes around your input variable you should use ffprobe instead of ffmpeg to get media file information. The output from ffmpeg is intended for informational purposes only and is not to be parsed by scripts: it is considered "fragile" and is not guaranteed to provide a standard, consistent format. Using ffprobe will also allow you to eliminate sed .

#!/bin/bash

# Output file path and name
echo "$1"

# Output average frame rate
ffprobe -loglevel error -select_streams v:0 -show_entries stream=avg_frame_rate -of default=noprint_wrappers=1:nokey=1 "$1"

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