How to create bash script to do/undo setting locale with one alias? - locale

How to create bash script (to make alias of it), doing this:
if LANG=en_US.UTF-8
then "unset LANG"
else "export LANG=en_US.UTF-8"

adding
en() {
if [[ $LANG == "en_US.UTF-8" ]]
then unset LANG
else export LANG=en_US.UTF-8
fi
}
to ~/.bash_profile works!

Related

Title of "gnome-terminal" is being overridden by .bashrc in Ubuntu

I need to open around 20 terminals on the same time and execute different command on each one ,and I'd like also to name each window with a different name.
I'm using something as follows:
gnome-terminal --title="some title goes here" -- bash -ic "ls; exec bash"
The new window is opened , shows the title some title goes here and after 1~2 seconds
it's being overridden and turns into the path that I'm running the command
gnome-terminal --title="some title goes here" -- bash -ic "ls; exec bash"
from.
Here is my .bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color|*-256color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u#\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u#\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user#host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u#\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
[ -f ~/.fzf.bash ] && source ~/.fzf.bash
# function
parse_git_branch() {
if [ -n "$(git rev-parse --git-dir 2> /dev/null)" ]; then
echo "($(git rev-parse --abbrev-ref HEAD)) "
fi
}
# environment customization
# PS1="[\t \D{%F} \u#\h \W\a]$ "
PS1="$PS1-[\t \D{%F}]$ "
export PS1="$PS1\$(parse_git_branch)"
# HSTR configuration - add this to ~/.bashrc
alias hh=hstr # hh to be alias for hstr
export HSTR_CONFIG=hicolor # get more colors
shopt -s histappend # append new history items to .bash_history
export HISTCONTROL=ignorespace # leading space hides commands from history
export HISTFILESIZE=10000 # increase history file size (default is 500)
export HISTSIZE=${HISTFILESIZE} # increase history size (default is 500)
# ensure synchronization between bash memory and history file
export PROMPT_COMMAND="history -a; history -n; ${PROMPT_COMMAND}"
# if this is interactive shell, then bind hstr to Ctrl-r (for Vi mode check doc)
if [[ $- =~ .*i.* ]]; then bind '"\C-r": "\C-a hstr -- \C-j"'; fi
# if this is interactive shell, then bind 'kill last command' to Ctrl-x k
if [[ $- =~ .*i.* ]]; then bind '"\C-xk": "\C-a hstr -k \C-j"'; fi
function changeTitle(){
if [[ -z "$ORIG" ]]; then
ORIG="$PS1"
fi
TITLE="\[\e]2;$*\a\]"
PS1="${ORIG}${TITLE}"
}
### ALIASES ###
alias k='kubectl'
Any idea how to fix this ?
The prompt set in PS1 contains screen control codes which overwrite the window title.
If you don't want the prompt to change your window title, take out the snippet which does that.
Here's a slight edit to let you set no_title_change in the calling shell. This would replace the similar snippet in your current .bashrc; the real change it that we change the variable $TERM to a slightly more complex (and slightly hacky) parameter expansion.
...
# If this is an xterm set the title to user#host:dir
# unless $no_title_change is set
case ${no_title_change-$TERM} in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u#\h: \w\a\]$PS1"
;;
*)
;;
esac
...
If you unconditionally want to remove the title-changing logic, just replace this snippet with nothing.
The use case of opening a separate terminal window for each in a set of tasks is dubious; a better practice generally is to run your tasks as background processes, each with output to a file. Then you can automate monitoring and logging for the entire scenario, and avoid silly problems like terminating a process by mistake by accidentally closing the wrong terminal window; and managing the processes remotely from multiple locations becomes feasible.

Improve function that adds aliases to .bashrc from command line

I wrote this function which I use to add aliases to .bashrc file.
The function works well but it's not complete, I would like to ask for confirmation from the user if the alias being added already exists and write the if condition in order to achieve the "modified" part of the code if confirmation is given, just like when you install a new package.
add_alias(){
d_alias=$1
d_command="$2"
replacing=alias|grep "alias $d_alias"
if [[ "$replacing" -ne 0 ]];
then
sed -i "/alias $d_alias/d" $HOME/.bashrc
echo "alias $d_alias modified in ~/.bashrc"
else
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$d_alias"'='"'$d_command'"',2' $HOME/.bashrc
source ~/.bashrc
echo "alias $d_alias added to ~/.bashrc"
fi
}
#auto-generated code
alias brc='source ~/.bashrc'
alias client='/home/user/workspace/client'
alias workspace='/home/user/workspace'
I'm adding an answer for future reference, credits to #4ae1e1 and #ArunSangal. Their suggestions are in the comments.
# TODO Room to improve - add_alias()
# Add new aliases to this .bashrc file
#-------------------------------------
add_alias(){
n_alias=$1
shift
n_command="$#"
replacing=$( alias $n_alias 2>/dev/null|wc -l )
if [[ "$replacing" = "1" ]];
then
b $n_alias # cat|grep .bashrc in color
read -p "Do you wish to overwrite this(these) alias(es)? [y/n]" yn
case $yn in
[Yy]* ) sed -i '/alias '"$n_alias"'/d' $HOME/.bashrc;
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$n_alias"'='"'$n_command'"',3' $HOME/.bashrc;
source ~/.bashrc;
echo "alias $n_alias modified in ~/.bashrc" ;;
[Nn]* ) echo "Operation canceled";;
* ) echo "Please answer yes or no.";;
esac
else
sed -i ':a;$!{N;ba};s,\(auto-generated code\),\1\nalias '"$n_alias"'='"'$n_command'"',3' $HOME/.bashrc
source ~/.bashrc
echo "alias $n_alias added to ~/.bashrc"
fi
}
alias aa='add_alias'
# end of add_alias()
# auto-generated code
alias cdn='ssh cdn'
alias cdn2='ssh cdn2'
alias sxdev64="ssh sxdev64"
alias csi="ssh csi"
alias malt="ssh malt"
This function adds an alias to both the current shell and to ~/.bash_aliases at the same time. I always test the alias manually before
submitting it to add-alias. It works well for me and I have been using it for a long time. Of course I don't run a production system.
YMMV.
add-alias ()
{
local name=$1 value="$2"
echo alias $name=\'$value\' >> ~/.bash_aliases
eval alias $name=\'$value\'
alias $name
}
You can add the bells & whistles.

Set environmental variables in a particular directory

This is a .bashrc question.
I would like to set "export FOO=bar" for .bashrc in a particular directory like .rvmrc.
I tried below.
$ touch ~/foo/.bashrc
$ echo 'export RAILS_ENV=development' >> ~/foo/.bashrc
$ cd foo/
$ env|grep RAILS_ENV
But RAILS_ENV shall be set nothing in this case.
If I set onto .rvmrc instead of .bashrc, it pass! But it is better way to set onto .bashrc because I do not need to install rvm environment.
Any solutions?
in your bashrc set this:
PROMPT_COMMAND='[[ $PWD == "/foo/bar/" ]] && export FOO=BAR || unset FOO'
The contents of the PROMPT_COMMAND variable will be executed every time your prompt is rewritten ( just before it's written actually ) the command above checks the $PWD variable ( which holds the current working directory of your shell ) against "/foo/bar" if it matches it exports your variable if it doesn't then the variable is unset.
EG
peteches#yog-sothoth$ PROMPT_COMMAND='[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO'
peteches#yog-sothoth$ pwd
/home/peteches
peteches#yog-sothoth$ cd test
peteches#yog-sothoth$ pwd
/home/peteches/test
peteches#yog-sothoth$ env | grep FOO
6:FOO=BAR
73:PROMPT_COMMAND=[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO
peteches#yog-sothoth$ cd ../
peteches#yog-sothoth$ pwd
/home/peteches
peteches#yog-sothoth$ env | grep FOO
72:PROMPT_COMMAND=[[ $PWD == "/home/peteches/test" ]] && export FOO=BAR || unset FOO
peteches#yog-sothoth$
If you don't mind to use a workaround, add this to your .bash_profile
mycd()
{
cd $1
if [ "$(pwd)" == "/your/folder/that/needs/env" ]; then
export RAILS_ENV=development
else
export RAILS_ENV=
fi;
}
alias cd=mycd
Everytime you move to a certain folder this will set your env variable or whatever you want
First, AFAIK, bash won't search for a .bashrc file in any other directory but your home -- at least, not by default.
Secondly, after writing new entries to your .bashrc, you should source .bashrc the file, so that modifications take place.
Check out direnv
direnv is an extension for your shell. It augments existing shells with a new feature that can load and unload environment variables depending on the current directory.
Basically checks for .envrc files located in the current or parent directories, and adjusts your environment variables accordingly.

SSH through Putty comes up with a "no such file or directory"

I'm trying to access out Linux server through Putty but for some reason after a somewhat successful login it just throws a "/bin/bash no such file or directory" then Putty closes.
Contents of bashrc:
# /etc/bashrc
# System wide functions and aliases
# Environment stuff goes in /etc/profile
# By default, we want this to get set.
# Even for non-interactive, non-login shells.
if [ $UID -gt 99 ] && [ "`id -gn`" = "`id -un`" ]; then
umask 002
else
umask 022
fi
# are we an interactive shell?
if [ "$PS1" ]; then
case $TERM in
xterm*)
if [ -e /etc/sysconfig/bash-prompt-xterm ]; then
PROMPT_COMMAND=/etc/sysconfig/bash-prompt-xterm
else
PROMPT_COMMAND='echo -ne "\033]0;${USER}#${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007"'
fi
;;
screen)
if [ -e /etc/sysconfig/bash-prompt-screen ]; then
PROMPT_COMMAND=/etc/sysconfig/bash-prompt-screen
else
PROMPT_COMMAND='echo -ne "\033_${USER}#${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\033\\"'
fi
;;
*)
[ -e /etc/sysconfig/bash-prompt-default ] && PROMPT_COMMAND=/etc/sysconfig/bash-prompt-default
;;
esac
# Turn on checkwinsize
shopt -s checkwinsize
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u#\h \W]\\$ "
fi
if ! shopt -q login_shell ; then # We're not a login shell
# Need to redefine pathmunge, it get's undefined at the end of /etc/profile
pathmunge () {
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
fi
}
# Only display echos from profile.d scripts if we are no login shell
# and interactive - otherwise just process them to set envvars
for i in /etc/profile.d/*.sh; do
if [ -r "$i" ]; then
if [ "$PS1" ]; then
. $i
else
. $i >/dev/null 2>&1
fi
fi
done
unset i
unset pathmunge
fi
# vim:ts=4:sw=4
What could be causing this?
Thanks!
Well bash is more than likely located at a different location on this linux box to /bin/bash
I've found this to be the case on different boxes and I've changed my .profile script in my home directory to not directly execute bash, could be a solution in your case. So when you log in you stay in the bourne shell, and then go into the bash shell only if you explicitly type bash.
Check your /etc/ssh/sshd_config to make sure that you don't have a chroot directory set. If you do, you will need to either create a bin directory in the chroot directory and either copy or link the necessary binaries into that directory.
Or you could always comment that line out in the config.
Either way, restart sshd and test.

Let gVim always run a single instance

Is there a way to let gVim only run a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance?
I know you can do that by passing --remote-tab-silent but I want to configure gvim so that this becomes the default behavior. i.e. I want to type gvim filename and make it act as if I passed the --remote-tab-silent option to it.
gVim 7.2
Edit
I'm on windows (vista)
If you are using the bash shell (on Linux/OS X/using Cygwin) is to add you ~/.bashrc file:
gvim () { command gvim --remote-silent "$#" || command gvim "$#"; }
On Windows I think you could have a gvim.bat batch-script to achieve the same..
gvim.exe -p --remote-tab-silent %1 %*
If gvim.exe isn't in your path
Run > Search "Environment"
Edit PATH var for current user or system.
It depends on your operating system and shell. Using linux you can always set up an alias like:
alias gvim='gvim --remote-tab-silent'
in your .bashrc (if you use bash as your login shell).
On windows see the Vim wiki for solution: http://vim.wikia.com/wiki/Launch_files_in_new_tabs_under_Windows .
I've found the --remote-tab-silent option in an alias to work for the most part except when I've wanted to pass options to gvim (e.g. gvim --serverlist) - in which case gvim treats the option as a literal filename which is no good as firstly that's not what you wanted and secondly you have to clean up the buffers from your now tainted vim session.
It's not practical to use another alias or resolve vim/gvim differently for some cases such as the following.
gvim
gvim /path/to/files
gvim --serverlist
gvim -p /path/to/file1 /path/to/file2
gvim -t tag filename
My solution is the following wrapper script around gvim (~/.bin/gvim) as Tom Veiner suggests but this will only use an existing server if none of the arguments are gvim options - otherwise, a new server is created.
#!/usr/bin/perl
use v5.10;
sub gvim { exec { '/usr/bin/gvim' } '/usr/bin/gvim', #_; }
if (scalar #ARGV) {
unshift #ARGV, '--remote-tab-silent' unless /^--?/ ~~ #ARGV;
gvim #ARGV
}
else {
chomp(my $serverlist = `gvim --serverlist`);
if (length $serverlist) {
gvim '--remote-send', '<Esc>:tabnew<CR>'
} else { gvim }
}
alias tvim="gvim --servername `gvim --serverlist | head -1` --remote-tab"
This make vim open a new file in new tab on same instance of vim. Source: http://eustaquiorangel.com/posts/477
Portable Wrapper Script:
I got a little tired of working around this in cygwin + windows so I finally did something about it. I started with the wrapper script defined above but I wound up making it a lot more robust and multi-env capable for *nix and Win.
#!/bin/bash
#bash wrapper for windows/cygwin gvim
#####################################################################
## Cygwin/*nix and Windows gvim wrapper script, alias friendly, path friendly
## Author: Matt Gregory (skyleach (AT) geemale (dot) com)
## Version: 1.5
## Date: Thu Jun 12 10:02:54 2014
## Known Bugs:
## Changes:
## Thu Jun 12 10:04:08 2014 : Initital posting to StackOverflow
#####################################################################
[[ -z ${WINVIM} ]] && WINVIM=true
[[ -z ${VIMRUN} ]] && export VIMRUN='' #scoping
if [[ ${WINVIM} = false ]]; then
[[ ! ${VIMRUN} ]] && VIMRUN='/bin/gvim'
ANS=$("${VIMRUN}" --serverlist | grep GVIM)
else
[[ ! "${VIMRUN}" ]] && VIMRUN='/cygdrive/c/Program Files/vim/vim74/gvim'
ANS=$(ps -Wsl | grep "${VIMRUN}" | sed -e "s/\s\+\([0-9]\+\).*/\1/g")
fi
[[ ! -z ${VIM} && ${WINVIM} = true ]] && export VIM=$(cygpath -wal "${VIM}")
RT="--remote-tab"
[[ $ANS ]] || unset RT
if [ ! -z ${DEBUG} ]; then
echo "WINVIM: ${WINVIM}"
echo "VIMRUN: ${VIMRUN}"
echo "ANS: ${ANS}"
echo "VIM: ${VIM}"
fi
#process arguments or stdin
if [ ${#} -ne 0 ]; then
[[ ! -z ${DEBUG} ]] && echo "Got arguments [${#}]:'${#}'"
for OFILE in "${#}"; do # if [ -f "${OFILE}" ] || [ -d "${OFILE}" ]; then
[[ -h ${OFILE} ]] && OFILE="$(readlink -f "${OFILE}")"
[[ ${WINVIM} == true ]] && OFILE=$(cygpath -wal "${OFILE}")
echo "\"${VIMRUN}\" --servername GVIM $RT \"${OFILE}\""
"${VIMRUN}" --servername GVIM $RT "${OFILE}" &
if [[ -z ${RT} ]] || [[ ! "${RT}" ]]; then
RT="--remote-tab"
sleep 5 #give gvim time to start up, running too fast messes things up
else
sleep .3 #shorter sleep for tabs
fi
#fi
done
else
while read OFILE; do
[[ -h ${OFILE} ]] && OFILE="$(readlink -f "${OFILE}")"
[[ ${WINVIM} == true ]] && OFILE=$(cygpath -wal "${OFILE}")
echo "\"${VIMRUN}\" --servername GVIM $RT \"${OFILE}\""
"${VIMRUN}" --servername GVIM $RT "${OFILE}" &
if [[ -z ${RT} ]] || [[ ! "${RT}" ]]; then
RT="--remote-tab"
sleep 3 #give gvim time to start up, running too fast messes things up
else
sleep .3 #shorter sleep for tabs
fi
done
fi
# vim: set filetype=sh:
How to use it effectively:
Install the above code into a script file on yor path somewhere
Add a WINVIM environment variable to windows or your ~/.bashrc file in order to set the default script behavior. true/use windows. false/use x11
alias some command to cygwin and/or windows gvim like so:
echo "alias gwrap='WINVIM=false ~/src/localscripts/wgwrap'" >> ~/.bashrc
echo "alias wgvim='wgwrap'" >> ~/.bashrc
NOTE: If the hard-coded paths to gvim are incorrect for your system you can edit the script directly, the alias(s) and/or add the environment variables WINVIM and/or VIMRUN. You can set them in the alias as I do above for gwrap or you can add them to your .bashrc or Windows system environment.
I often find that I want to go to a specific place in a file. The only way I found to do this was:
gvim --remote-send '^[:tabnew +$lineno $filename ^M'
where ^[ is esc (typed ctrl-v esc) and ^M is enter (ctrl-v enter).
Hope this helps. If anyone understands how to use --remote-expr, give me a shout.
I'm using TotalCommander for file browsing. It lets you press "F4" to edit the file. So in the "Editor for F4" option window, you just need to do the following:
C:\Program Files (x86)\Vim\vim73\gvim.exe --remote-tab-silent
Works on my win7 64bit machine.
The solutions above don't launch the gvim server on first execution, so I use:
ANS=`pgrep -fx "$VIM"`
# Launch server if needed
if [[ ! $ANS ]]; then
$VIM
fi
# Now open the file
if [[ $1 ]]; then
$VIM --remote-tab "$#"
fi
modified from https://stackoverflow.com/a/15335004/214686
NOT For WINDOWS
I use MacVim (snapshot 73).
Add this to your .bash_profile.
It won't generate "NO NAME" and error message.
vi() {
if [[ `mvim --serverlist` == 'VIM' ]]; then
command mvim --remote-tab-silent "$#"
else
command mvim "$#"
fi
}
Using MacVim, I discovered the default servername was simply VIM. Sticking with that theme, I threw the following function in my bashrc and it works like a charm:
mvim() { ~/bin/mvim --servername VIM --remote-tab-wait-silent $* & }
gvimt () { [ $# -ne 0 ] && command gvim --remote-silent-tab $# || command gvim $#; }
I'm actually using
gvim () {
if [ "$#" -gt 0 ]
then
gvim --remote-tab-silent "$#" &
else
gvim "$#" &
fi
}
It kills errors and only used the flag when there is a parameter
Change your path in registry
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\gvim.exe\shell\edit\command
"Path2gvim\gvim.exe" "%1" -->
"Path2gvim\gvim.exe" --remote-tab-silent "%1"

Resources