shell

Checking for Vim Shell

Sometimes, it’s easy to forget when you’re using :sh from Vim. One way to check whether the current shell was started from Vim is the $VIMRUNTIME environment variable.

Normal shell:

$ echo $VIMRUNTIME
 

Shell from Vim:

$ echo $VIMRUNTIME
/usr/local/share/vim/vim81

See original question here.

History Substitution

Use !! for history substitution in shells like bash and zsh.

$ ag -l apple
a.txt
b.js
c.scss
$ vim $(!!)
-> equivalent to running vim $(ag -l apple)

Tags: shell

Vi Mode in any shell (Zsh, Fish and even Bash!)

VI Mode in any shell

Assuming that you love using VIM and the terminal, here’s a cool mode that can be activated on Zsh or any shell rather. (I am using Zsh, so, I will talk about it)

Enable vim mode on Zsh by adding this line into your .zshrc.
bindkey -v
Basically this means to enable vim mode

When this is enabled, refresh your shell and you can insert texts after pressing i and if you want to run any text-object related moves, just press Esc and the normal hjkl, b, w, ciw, diw, ^, 0, $ will work! Exactly like in vim!

Sum number with AWK

Assume that you have a text file named test.txt with a list of numbers:

5
6
1
3
4
5
1

To calculate the sum in terminal, you can use:

cat test.txt | awk '{sum += $1} END {print sum}'

For more, refer to StackExchange Answer,

Test String with Regex

You can test a string with regex in shell script like this:

email="[email protected]"
if [[ "$email" =~ "[a-z]+@[a-z]+\.com" ]]; then
    echo "Valid email"
else
    echo "Invalid email"
fi

Tags: shell

Checking Return Code

Use $? to get the return code of the last command.

$ cat example.txt
$ echo $?
1
$ touch example.txt
$ cat example.txt
$ echo $?
0

Tags: shell

Editing Long Commands in Shell

When typing long commands in the shell, you can do ctrl-x-e to invoke your editor based on the environment variable $EDITOR. If you use Vim, edit the command, and do :wq. This will bring you back to the shell with the edited command.

Tags: shell

Operating only on changed files

In some occasion, after making some changes to different files, we might want to apply some operations only on the changed files.

Assuming you’re using git for version control, we can use git diff --name-only to get a list of changed files.

In shell, we can use $(<command) to run a command and capture its output.

Combining these two, we can apply an operation on changed files by:

$ <command> $(git diff --name-only)

Use Case

Previously I am not using any code formatter on my client project. Even though, I can run the formatter directly on the whole project, I am afraid that some code might break (since I don’t have a full test coverage).

Hence, I plan to slowly format my code whenever I make any changes with this command:

bundle exec standardrb $(git diff --name-only) --fix

References