你能帮我创造bash脚本:设置的权限,这是脚本的用于具有定义的扩展为第二脚本参数值被定义为脚本的第三个参数中的所有文件的参数的目录。
因为你很可能新的抨击和分析参数传递给脚本,我会告诉你一个基本的方法来完成你所描述的。
#!/bin/bash
# stop execution of the script if an error occurs suchs as when the
# directory in argument 1 does not exists
set -e
dir=$1 # get the directory from the first argument
ext=$2 # get the extension from the second argument
perms=$3 # the third argument is the permissions you're going to pass to `chmod`
cd "$dir" # change directory to the target directory
# use regular filename expansion with the extension in
# $ext and supply `chmod` with the permissions in $perms
chmod "$perms" *"$ext"
如果您保存这是extchmod.sh
和可执行成功了,你会像这样运行:
$ ./extchmod.sh target_directory .txt 644
$ ./extchmod.sh target_directory .sh 755
这将改变所有文件target_directory
与.txt
扩展权限644下的所有文件与.sh
扩展权限755。
我要指出,在bash / SH,$ 1的第一个参数的值,$ 2有第二个参数的值,依此类推。 $ @永远是包含所有的参数数组。
我会建议使用find
和xargs
的组合
$ find /home/mirko/example/ -maxdepth 1 -name '*.jpg' -print0 | xargs -0 chmod 644
如果你仍然想为一个shell脚本,我建议是这样的:
#!/usr/bin/env bash
scriptname=$(basename $0)
if [ $# -ne 3 ]; then
echo "usage: $scriptname path extension mode" >&2
echo "example: $scriptname /home/foo/pictures/ jpg 644" >&2
exit 1
fi
directory=$1
extension=$2
mode=$3
find "$directory" -maxdepth 1 -name "*.${extension}" -print0 | xargs -0 chmod "$mode"
if [ $? -ne 0 ]; then
echo "$scriptname: ERROR: command returned unsuccesfull" >&2
exit 1
fi