如何从 bash 函数打开编辑器?
我有一个简单的函数来打开编辑器:
open_an_editor() { nano "$1" }
如果像 open_an_editor file.ext
那样调用,它就可以工作。但是,如果我需要从函数中获取一些输出 - smth=$(open_an_editor file.ext)
- 我看不到编辑器,脚本就会卡住。我在这里缺少什么?
更新:我正在尝试编写一个函数,如果脚本参数中未给出该值,则该函数会要求用户在编辑器中写入一个值。
#!/bin/bash open_an_editor() { if [ "$1" ] then echo "$1" return 0 fi tmpf=$(mktemp -t pref) echo "default value, please edit" > "$tmpf" # and here the editor should show up, # allowing user to edit the value and save it # this will stuck without showing the editor: #nano "$tmpf" # but this, with the help of Kimvais, works perfectly: nano "$tmpf" 3>&1 1>&2 2>&3 cat "$tmpf" rm "$tmpf" } something=$(open_an_editor "$1") # and then I can do something useful with that value, # for example count chars in it echo -n "$something" | wc -c
因此,如果使用参数 ./script.sh "A value"
调用脚本,该函数将仅使用该参数并立即回显 7 个字节。但如果不带参数./script.sh
调用 - nano 应该弹出。
I have a simple function to open an editor:
open_an_editor() { nano "$1" }
If called like open_an_editor file.ext
, it works. But if I need to get some output from the function — smth=$(open_an_editor file.ext)
— I cannot see the editor, script just stucks. What am I missing here?
Update: I am trying to write a function which would ask the user to write a value in editor, if it wasn't given in script arguments.
#!/bin/bash open_an_editor() { if [ "$1" ] then echo "$1" return 0 fi tmpf=$(mktemp -t pref) echo "default value, please edit" > "$tmpf" # and here the editor should show up, # allowing user to edit the value and save it # this will stuck without showing the editor: #nano "$tmpf" # but this, with the help of Kimvais, works perfectly: nano "$tmpf" 3>&1 1>&2 2>&3 cat "$tmpf" rm "$tmpf" } something=$(open_an_editor "$1") # and then I can do something useful with that value, # for example count chars in it echo -n "$something" | wc -c
So, if the script was called with an argument ./script.sh "A value"
, the function would just use that and immediately echo 7 bytes. But if called without arguments ./script.sh
— nano should pop up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要的输入是编辑后的文件,那么您显然需要在执行
open_an_editor filename
之后cat filename
如果您确实需要编辑器的输出,那么您需要交换 stderr 和 stdin 即:
nano "$1" 3>&1 1>&2 2>&3
如果您需要“友好”的用户输入,请参阅这个问题关于如何使用whiptail
If the input you need is the edited file, then you obviously need to
cat filename
after you do theopen_an_editor filename
If you actually need the output of the editor, then you need to swap stderr and stdin i.e:
nano "$1" 3>&1 1>&2 2>&3
If yo need 'friendly' user input, see this question on how to use whiptail
如果您需要从函数获取输出并将其存储在变量中,则只需显示文件中的内容即可。
if you need to get output from function and store in variable, you just display what's in file.
如果您只想让用户输入一个值,那么
read
就足够了:If all you want is for a user to enter a value then
read
is enough: