我看到有人发布了以下答案来说明如果通过和继续之间的区别.我知道"a"列表是[0,1,2],我只是不知道"if not element"的结果是什么?为什么使用continue时,0不打印,只打印1和2?当a = 0时,"if not element"是"if not 0",它有特殊含义吗?
>>> a = [0, 1, 2]
>>> for element in a:
... if not element:
... pass
... print(element)
...
0
1
2
>>> for element in a:
... if not element:
... continue
... print(element)
...
1
2
Run Code Online (Sandbox Code Playgroud) 我尝试在bash中使用读/写文件描述符,以便我可以删除文件描述符后面引用的文件,如下所示:
F=$(mktemp)
exec 3<> "$F"
rm -f "$F"
echo "Hello world" >&3
cat <&3
Run Code Online (Sandbox Code Playgroud)
但该cat命令没有输出.如果我使用单独的文件描述符进行读写,我可以实现我想要的:
F=$(mktemp)
exec 3> "$F"
exec 4< "$F"
rm -f "$F"
echo "Hello world" >&3
cat <&4
Run Code Online (Sandbox Code Playgroud)
打印Hello world.
我怀疑当你从写入切换到读取时,bash不会自动寻找文件描述符的开头,以下bash和python代码的组合证实了这一点:
fdrw.sh
exec 3<> tmp
rm tmp
echo "Hello world" >&3
exec python fdrw.py
Run Code Online (Sandbox Code Playgroud)
fdrw.py
import os
f = os.fdopen(3)
print f.tell()
print f.read()
Run Code Online (Sandbox Code Playgroud)
这使:
$ bash fdrw.sh
12
$ # This is the prompt reappearing
Run Code Online (Sandbox Code Playgroud)
有没有办法实现我想要的只是使用bash?
我想在将文件添加到Git索引之前自动格式化我的文件.现在,我有一个预提交钩子,看起来像这样:
#!/bin/bash
set -e
exec 1>&2
workingext="working.$$"
ext="bak.$$"
git diff -z --cached --name-only | egrep -z '\.(pl|pm|t)$' | \
while read -d'' -r f; do
# First modify the file in the index
mv "$f" "$f.$workingext"
git show :"$f" > "$f"
perl -c "$f"
perltidy -pbp -nst -b -bext="$ext" "$f";
rm -f "$f.$ext"
git add "$f"
mv "$f.$workingext" "$f"
# Then the working copy
perl -c "$f"
perltidy -pbp -nst -b -bext="$ext" "$f";
rm -f "$f.$ext"
done
Run Code Online (Sandbox Code Playgroud)
基本上,我备份工作副本,检查索引副本,格式化它们,将它们添加到索引,然后还原工作副本并格式化它们,以便工作副本和索引副本之间的差异也不会增长大.我首先检查文件的语法,perl -c …
bash ×1
continue ×1
file-io ×1
git ×1
githooks ×1
if-statement ×1
linux ×1
python ×1
read-write ×1
rust ×1
rust-cargo ×1
unix ×1