从bash中的文件路径获取基名 [英] Get basename from filepath in bash
问题描述
我正在尝试使用$ 1变量运行bash命令,该变量包含文件名及其路径.
I am trying to run a bash command using $1 variable which contains a filename and its path.
我只想将文件名记录到output.txt文件中,但是我很难从变量中删除路径.
I want to log only the filename to an output.txt file but I am having difficulty stripping out the path from the variable.
我尝试了以下操作:
file=$(basename $1)
echo ${file} >> output.txt
file=$(basename $1)
echo file >> output.txt
echo "basename $1" >> output.txt
它们都不起作用,返回数据"或文件"
None of them work, either return 'Data' or 'file'
推荐答案
通常来说,这里有 2个陷阱:
neglecting to double-quote parameter and variable references -
$1
or$var
- and command substitutions -$(...)
- making them subject to word splitting and globbing, which could break the overall command, or, worse, introduce security vulnerabilities.
次要的是,确保命令 operand 不会误认为 option ,如果它恰好启动了带有-
字符,使用-
表示其后的所有内容均应解释为 operand .
less importantly so, making sure that a command operand isn't mistaken for an option, if it happens to start with a -
character, by using --
to signal that everything following it is to be interpreted as an operand.
分配到变量(双引号可选,但推荐):
Assigning to a variable (double-quoting optional, but recommended):
# OK - but note that the $1 inside the $(...) IS double-quoted,
# because command substitutions are "their own world".
file=$(basename -- "$1")
# Better, just to get into the habit of double-quoting:
file="$(basename -- "$1")"
使用变量-始终双引号(除非您明确希望分词和遍历):
Using the variable - always double-quote (unless you explicitly want word-splitting and globbing):
echo "${file}" >> output.txt
关于为什么您的尝试不起作用:
-
echo文件>>output.txt
无效,因为要引用变量file
,您必须$
-前缀(即$ file
,并且由于上述原因,实际上几乎总是"$ file"
).
echo file >> output.txt
didn't work, because in order to reference variablefile
you must$
-prefix it (i.e.,$file
and, for the reasons stated above, virtually always as"$file"
).
echo"basename $ 1">>output.txt
不起作用,因为在双引号字符串内扩展了参数 $ 1
时,您需要命令替换-这里是 $(基本名称"$ 1")
-将命令嵌入在双引号字符串中.
echo "basename $1" >> output.txt
didn't work, because while parameter $1
is expanded inside the double-quoted string, you need a command substitution - here, $(basename "$1")
- to embed commands in a double-quoted string.
file = $(basename $ 1)
,由于缺少 $ 1
的双引号,因此 only 与 $ 1
值,不包含任何外壳元字符(包括空格),以及不以-
开头的值; echo $ {file}>>再次由于缺少双引号而导致output.txt
再次无意中更改了 $ file
的值.
file=$(basename $1)
, due to lack of double-quoting of $1
, would only work with $1
values that contain no shell metacharacters (including spaces), and values that don't start with -
; echo ${file} >> output.txt
- again due to lack of double-quoting - could then inadvertently alter the value of $file
again.
这篇关于从bash中的文件路径获取基名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!