basename
basename命令在shell编程中还是非常实用的。
1.对于文件路径,可以去除文件的路径和文件的后缀输出文件名称。
2.对于目录路径,可以去除目录路径输出目录名称。
参考文档
- basename 源代码
https://github.com/coreutils/coreutils
- basename 文档
http://www.maizure.org/projects/decoded-gnu-coreutils/
架构图
例子
1.查看help/version
basename --help
basename --version
2. basename 不加任何参数选项
basename ~/workspace/shell_command/base_name.sh
basename ~/workspace/shell_command/base_name.sh .sh
输出结果
base_name.sh
base_name
3. 参数选项 -a, --multiple 支持一次处理多个路径字符串,并把基本名称打印到终端
basename -a ~/workspace/shell_command/base_name.sh ~/workspace/shell_command/hostid_test.sh
输出结果
base_name.sh
hostid_test.sh
对于目录路径的处理
basename -a ~/workspace/shell_command ~/workspace/shell_command
输出结果
shell_command
shell_command
4. 参数选项 -s, --suffix 移除文件后缀
basename -s .sh base_name.sh
basename -s .sh ~/workspace/shell_command/base_name.sh
输出结果
base_name
base_name
5.参数选项 -z,--zero 在输出处理过的路径字符串后,不输出任何东西。在不加此参数时,会在输出的结果后,会换到下一行。
basename ~/workspace/shell_command/base_name.sh
basename -z ~/workspace/shell_command/base_name.sh
输出结果
6.在shell脚本中的使用
#!/bin/bash
declare -a dirname
declare -a filename
file_path="/home/maobin/workspace/shell_command/hostid_test.sh"
file_path2="/home/maobin/workspace/shell_command/base_name.sh"
dir_path="/home/maobin/workspace/shell_command"
dir_path2="/home/maobin/workspace"
echo "case 1"
filename=`basename $file_path`
echo "filename:${filename}"
dirname=`basename $dir_path`
echo "dirname:${dirname}"
echo -e "\n"
echo "case 2"
filename=`basename -a $file_path $file_path2`
echo "filename: ${filename[@]}"
dirname=`basename -a $dir_path $dir_path2`
echo "dirname:${dirname[@]}"
filename=`basename -z -a $file_path $file_path2`
echo "filename: ${filename[@]}"
echo -e "\n"
echo "case 3"
filename=`basename -s .sh $file_path`
echo "filename:${filename}"
filename=`basename $file_path .sh`
echo "filename:${filename}"
filename=`basename -s .sh -a $file_path $file_path2`
echo "filename: ${filename[@]}"
echo -e "\n"
输出结果
case 1
filename:hostid_test.sh
dirname:shell_command
case 2
filename: hostid_test.sh
base_name.sh
dirname:shell_command
workspace
base_name.sh: line 28: warning: command substitution: ignored null byte in input
filename: hostid_test.shbase_name.sh
case 3
filename:hostid_test
filename:hostid_test
filename: hostid_test
base_name