内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
在Bash中,我希望创建一个函数,返回与特定模式匹配的最新文件的文件名。例如,我有一个文件目录,如:
Directory/ a1.1_5_1 a1.2_1_4 b2.1_0 b2.2_3_4 b2.3_2_0
我要以‘b2’开头的最新文件。我怎么在bash做这件事?我要把这个放在我的~/.bash_profile脚本
。
这是可能你所需的Bash函数:
# Print the newest file, if any, matching the given pattern # Example usage: # newest_matching_file 'b2*' # WARNING: Files whose names begin with a dot will not be checked function newest_matching_file { # Use ${1-} instead of $1 in case 'nounset' is set local -r glob_pattern=${1-} if (( $# != 1 )) ; then echo 'usage: newest_matching_file GLOB_PATTERN' >&2 return 1 fi # To avoid printing garbage if no files match the pattern, set # 'nullglob' if necessary local -i need_to_unset_nullglob=0 if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then shopt -s nullglob need_to_unset_nullglob=1 fi newest_file= for file in $glob_pattern ; do [[ -z $newest_file || $file -nt $newest_file ]] \ && newest_file=$file done # To avoid unexpected behaviour elsewhere, unset nullglob if it was # set by this function (( need_to_unset_nullglob )) && shopt -u nullglob # Use printf instead of echo in case the file name begins with '-' [[ -n $newest_file ]] && printf '%s\n' "$newest_file" return 0 }