Coming up on another demo, I wondered if there is a way to make a series of commands easy to execute. The approach I used up to here was to copy the commands to a separate file and then copy paste the commands into my bash shell.
I can easily access previous command history by pressing “Ctrl+R” on the cmd line. So can I push commands into history and have them be readily available? Apparently I can.
Step 1: I create a text file, like the example below. I named the file history-cmds.txt
gcloud resource-manager folders create $FOLDER --organization=$ORG_ID
gcloud compute instances create $RES_NAME --project=$PROJECT_ID --zone=$ZONE
gcloud cloud-shell ssh --authorize-session # connect to cloud shell for current project
Step 2: Add it to history.
history -s “$(<history-cmds.txt)”
Step 3: Now you should be able to see it when running history and re-run them. You can use the “Ctrl+R” approach or you could find the number in history and run it like so:
With the environment variable approach, it also becomes easy to re-use the same command with different values. Note how you can also add comments at the end to help you understand what the command is doing.
I updated the simple push of the file’s lines with an additional filter for lines starting with # so that I can add comments.
history -s “$(sed ‘/^[ \t]*#/d’ < ~/coding/gcloud/history-cmds.txt)”
- I have set the option in my .bash_profile/.profile to not have duplicates as shown below. Forcing commands into history does not seem to respect that. However, if you run any of those commands, duplicates are removed.
# Avoid duplicates
- This was tried on bash shell on a MacOS.