Difference between revisions of "Bash"
Line 78: | Line 78: | ||
echo "arg: $var" | echo "arg: $var" | ||
done | done | ||
+ | |||
+ | == Previous command arguments == | ||
+ | To the the arguments from the previous command. | ||
+ | |||
+ | !^ first argument | ||
+ | !$ last argument | ||
+ | !* all arguments | ||
+ | !:2 second argument | ||
+ | |||
+ | !:2-3 second to third arguments | ||
+ | !:2-$ second to last arguments | ||
+ | !:2* second to last arguments | ||
+ | !:2- second to next to last arguments | ||
+ | |||
+ | !:0 the command | ||
+ | !! repeat the previous line, good with sudo |
Latest revision as of 15:05, 3 August 2023
Contents
- 1 Keyboard Shortcuts
- 2 One line conditional
- 3 Check for environment variable
- 4 Change the command prompt.
- 5 Alias
- 6 Edit in VIM
- 7 Echo commands
- 8 To set the CD Path
- 9 Alternative Screen
- 10 Temporary Environment Variables for Scripts
- 11 Exit script on error
- 12 Loop through argument variables.
- 13 Previous command arguments
Keyboard Shortcuts
To send the current line to VIM for editing.
ctrl+x ctrl+e
One line conditional
Both the following lines will write to the screen "false"
[[ 1 == 0 ]] || echo "text"
[[ 1 == 1 ]] && echo "text"
Check for environment variable
This will check to see if an variable is set
if [[ -z "$var" ]]; then echo "var is not set" fi
Change the command prompt.
To change the command prompt, export the below value.
export PS1=">"
or
export PS1="${ret_status} %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)"
Alias
To find the command associated with an alias.
type [alias_name]
To list all aliases, just type 'alias'.
alias
To create an alias.
alias myproject='cd /Users/jfreier/Projects/my_project'
Edit in VIM
To bring a command line in to VIM for editing
ctrl+x ctrl+e
Echo commands
This will print all commands that are ran.
set -x
To set the CD Path
$CDPATH
Alternative Screen
This happens when you run a command a new screen appears and then is closed when done.
To turn this feature off.
export LESS="-FRX"
This new screen is actually LESS and it just needs different flags.
Temporary Environment Variables for Scripts
If you have a script or command that uses environment variables, you can set one time variables be just prefixing the comment with the environment variable and command.
Example
echo_env_var.sh
#!/bin/bash echo $JOHN_FREIER
Command
# JOHN_FREIER=1 ./echo_env_var.sh
Exit script on error
To immediately exit a script when an error happens use the following command.
set -e
Loop through argument variables.
This sniplet will loop through the arguments of a script.
for var in "$@" do echo "arg: $var" done
Previous command arguments
To the the arguments from the previous command.
!^ first argument !$ last argument !* all arguments !:2 second argument !:2-3 second to third arguments !:2-$ second to last arguments !:2* second to last arguments !:2- second to next to last arguments !:0 the command !! repeat the previous line, good with sudo