Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I saw that with zsh vared you can edit on the fly the specified environment variable. Is there an equivalent command for bash?
Thanks

share|improve this question
2  
This might work for you: function vared { tmpfile=$( mktemp -t vared.XXXX ) ; echo "${!1}" > "$tmpfile" ; vim "$tmpfile" && export $1=$( cat "$tmpfile" ) ; rm "$tmpfile" ; }. Call as e.g. vared PATH, edit the value in vim and save to change the environment variable. (mktemp works differently depending on OS, this call seems to work mostly as intended on RHEL and OS X). –  Daniel Beck May 9 '13 at 13:16
    
Thanks, it's good enough for me, though not cool as zsh ;) If you'd like to provide it as an answer I will accept it. –  Carlo May 9 '13 at 13:28

1 Answer 1

up vote 4 down vote accepted

I'm not aware of anything that works like zsh's vared in bash, out of the box.

However, you can define a function that'll allow you to edit an environment variable's value using e.g. vim:

function vared {
  [[ $# -eq 1 ]] || { echo "Usage: vared VARNAME" >&2 ; return 1 ; }
  tmpfile=$( command mktemp -t vared.XXXX )
  echo "${!1}" > "$tmpfile"
  command vim "$tmpfile" && export $1="$(< "$tmpfile" )"
  command rm "$tmpfile"
}

Call it as vared PATH.

What does it do? It creates a temporary file, writes the current value of the specified variable into the file, and opens vim with the temp file as argument. Now you're expected to edit the value, save, and exit vim (you can exit without saving the file to skip saving changes). Afterwards, the contents of the file are set as the new variable value, the whole thing gets exported, and the temp file is removed. command is necessary to skip shell alias and function lookups, e.g. an rm alias to rm -i would ask before deleting the file at the end otherwise.

If the variable doesn't exist or isn't an environment variable, it will be afterwards.

share|improve this answer
    
+1. I'd use $VISUAL instead of hardcoding vim, and you can use $(< "$tmpfile") instead of cat -- $(< is a bash builtin –  glenn jackman May 9 '13 at 14:06
    
@glennjackman Thanks for the suggestions. I removed the UUOC. Regarding VISUAL: It's not set by default (at least on OS X), and checking whether it exists and adding a fallback (that would need to be personalized anyway) would unnecessarily increase the complexity here. –  Daniel Beck May 9 '13 at 14:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.