There will a time when we need to run a long or complex command in bash. I found myself in this situation when I play around with elasticsearch today. I need to run many curl command with long body like the below.

curl -XGET localhost:9200/megacorp/employee/_search?pretty -d '{
"query": {
"filtered": {
"filter": {
"range": {
"age": {
"gt": 30
}
}
},
"query": {
"match": {
"last_name": "smith"
}
}
}
}
}'


Usually I copy paste the command. When I need to edit it, I will use bash line editing feature such as ctrl a to go to beginning of command, ctrl e to go to end of command, ctrl arrow to move between word, ctrl k to kill from cursor to the end of line or ctrl u to kill from cursor to start of line and combined with inline editing of what need to change. It works but not fun. We cannot move between word easily and often we hit enter key or up down arrow accidentally before completing the command.

Here come the great solution: ctrl x ctrl e. After entering that, bash will open the editor and bring in whatever in the current shell command. After editing with more seamlessly in editor, just save the change and exit to execute the edited command.

Environment variable EDITOR will determine what editor to open when running that key. To override it, just set the env variable to whatever you like it such as export EDITOR=vim or you can update bash_profile so that the change will be persistent.