too*_*oop 117 unix linux bash shell scripting
我知道你可以mkdir创建一个目录并touch创建一个文件,但是没有办法一次完成这两个操作吗?
即如果我想在文件夹other不存在时执行以下操作:
cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
Run Code Online (Sandbox Code Playgroud)
错误:
cp: cannot create regular file `/my/other/path/here/cpedthing.txt': No such file or directory
Run Code Online (Sandbox Code Playgroud)
有没有人想出一个功能作为解决方法?
evo*_*pid 131
使用&&两个命令在一个外壳线面相结合:
COMMAND1 && COMMAND2
mkdir -p /my/other/path/here/ && touch /my/other/path/here/cpedthing.txt
Run Code Online (Sandbox Code Playgroud)
注意:以前我建议使用;分隔这两个命令,但正如@trysis指出的那样,&&在大多数情况下使用它可能更好,因为如果COMMAND1失败COMMAND2也不会执行.(否则,这可能会导致您可能没有预料到的问题.)
Jon*_*art 77
您需要先创建所有父目录.
FILE=./base/data/sounds/effects/camera_click.ogg
mkdir -p "$(dirname "$FILE")" && touch "$FILE"
Run Code Online (Sandbox Code Playgroud)
如果您想获得创意,可以创建一个功能:
mktouch() {
if [ $# -lt 1 ]; then
echo "Missing argument";
return 1;
fi
for f in "$@"; do
mkdir -p -- "$(dirname -- "$f")"
touch -- "$f"
done
}
Run Code Online (Sandbox Code Playgroud)
然后像任何其他命令一样使用它:
mktouch ./base/data/sounds/effects/camera_click.ogg ./some/other/file
Run Code Online (Sandbox Code Playgroud)
Iva*_*ves 21
用/ usr/bin/install做:
install -D /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt
Run Code Online (Sandbox Code Playgroud)
当您没有源文件时:
install -D <(echo 1) /my/other/path/here/cpedthing.txt
Run Code Online (Sandbox Code Playgroud)
Jav*_*ier 13
#!/bin/sh
for f in "$@"; do mkdir -p "$(dirname "$f")"; done
touch "$@"
Run Code Online (Sandbox Code Playgroud)
Jör*_*yer 12
你可以分两步完成:
mkdir -p /my/other/path/here/
touch /my/other/path/here/cpedthing.txt
Run Code Online (Sandbox Code Playgroud)
Sgn*_*gnl 12
这就是我要做的:
mkdir -p /my/other/path/here && touch $_/cpredthing.txt
这里,$_是一个变量,表示我们在行执行的上一个命令的最后一个参数.
与往常一样,如果您想查看输出可能是什么,可以使用echo命令对其进行测试,如下所示:
echo mkdir -p /code/temp/other/path/here && echo touch $_/cpredthing.txt
哪个输出为:
mkdir -p /code/temp/other/path/here
touch /code/temp/other/path/here/cpredthing.txt
Run Code Online (Sandbox Code Playgroud)
作为奖励,您可以使用大括号扩展一次编写多个文件,例如:
mkdir -p /code/temp/other/path/here &&
touch $_/{cpredthing.txt,anotherfile,somescript.sh}
Run Code Online (Sandbox Code Playgroud)
再次,完全可测试echo:
mkdir -p /code/temp/other/path/here
touch /code/temp/other/path/here/cpredthing.txt /code/temp/other/path/here/anotherfile /code/temp/other/path/here/somescript.sh
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125971 次 |
| 最近记录: |