我发现有些人在编写 bash 脚本时会在 if else 语句中定义局部变量,如示例 1
示例1:
#!/bin/bash
function ok() {
local animal
if [ ${A} ]; then
animal="zebra"
fi
echo "$animal"
}
A=true
ok
Run Code Online (Sandbox Code Playgroud)
再举个例子,这是一样的:
示例2:
#!/bin/bash
function ok() {
if [ ${A} ]; then
local animal
animal="zebra"
fi
echo "$animal"
}
A=true
ok
Run Code Online (Sandbox Code Playgroud)
因此,上面的示例打印了相同的结果,但哪一个是应该遵循的最佳实践。我更喜欢示例 2,但我看到很多人在函数内声明局部变量,如示例 1。最好在顶部声明所有局部变量,如下所示:
function ok() {
# all local variable declaration must be here
# Next statement
}
Run Code Online (Sandbox Code Playgroud) 我是 Lua 新手,我对 Lua 中的内存管理有疑问。
问题1)在使用using调用函数时io.popen(),我看到很多Lua程序员在usingpopen()函数后写了一个close语句。请问这是什么原因呢?例如,为了演示,请看以下代码:
handle = io.popen("ls -a")
output = handle:read("*all")
handle:close()
print(output)
handle = io.popen("date")
output = handle:read("*all")
handle:close()
print(output)
Run Code Online (Sandbox Code Playgroud)
我听说Lua可以自己管理内存。那么我真的需要handle:close像上面那样写吗?如果我忽略这个handle:close()语句并像这样写它,记忆会发生什么?
handle = io.popen("ls -a")
handle = io.popen("date")
output = handle:read("*all")
Run Code Online (Sandbox Code Playgroud)
问题2)从 中的代码来看,从内存占用的角度来看,最后的语句question 1是否可以只写一行而不是这样的两行?:handle:close()
handle = io.popen("ls -a")
output = handle:read("*all")
-- handle:close() -- dont close it yet do at the end
print(output)
handle = io.popen("date") -- this use the same variable `handle` previously
output = …Run Code Online (Sandbox Code Playgroud) 我有以下内容,output.txt它只包含 2 列来演示:
Test1 Test1-IS-OK
Test2 Test2-IS-NOT
Test3 Test3-IS-OK
Test4 Test4-IS-OK
Test5 Test5-IS-NOT
Run Code Online (Sandbox Code Playgroud)
然后我的 bash 脚本有以下代码:
#!/bin/bash
output="output.txt"
a=$(awk '{ print $1 }' $output)
b=$(awk '{ print $2 }' $output)
while IFS=" " read -r $a $b
do
echo "LOG: $a and $b"
done < "$output"
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
./test.sh: line 13: read: `Test1-IS-OK': not a valid identifier
Run Code Online (Sandbox Code Playgroud)
我需要有这样的输出
LOG: Test1 and Test1-IS-OK
LOG: Test2 and Test2-IS-NOT
LOG: Test3 and Test3-IS-OK
LOG: Test4 and Test4-IS-OK
LOG: Test5 and Test5-IS-NOT
Run Code Online (Sandbox Code Playgroud)
但是代码不起作用。从文件中循环这 …