简体   繁体   中英

Exporting builtin variables in bash script

That might be a trivial question, but what is the right way to use builtin variables in a shell script? For example, if I want to write a script that opens default text editor, which is specified in $EDITOR. Just using

export EDITOR

won't help. I found out that defining EDITOR variable helps to solve that problem:

#!/bin/bash    
export EDITOR=vim
$EDITOR

The above will work, but is there a way to export the variable without defining it? Thanks in advance.

EDITOR is not a "builtin" variable, and you can export it (ie make it an environment variable) whenever you like. Nothing magical here. While it is true that bash interprets this variable in certain situations, it is quite common that applications access this variable, when they want to launch an editor, so in practice, EDITOR is usually exported. For example, I have in my .zshrc and .bashrc the line

export EDITOR=nano

To your question: You can export a varible with an empty falue, like this

export EDITOR=

but I don't see what you will gain from it.

If you just want to ensure, that your shell script and all descendent processes have EDITOR set, a common idiom is

: ${EDITOR:=vim}
export EDITOR

If the user of your script doesn't define this variable, it is set here - you just need two lines, because bash syntax does not permit to combine this into a single one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM