How can I avoid certain lines from .bashrc and .inputrc from being loaded in tmux? - readline

I have these lines in my .inputrc:
"(": "\C-v()\ei"
"[": "\C-v[]\ei"
"{": "\C-v{}\ei"
"\"": "\C-v\"\C-v\"\ei"
"\'": "\C-v\'\C-v\'\ei"
This autocloses quotes and brackets in a terminal. But it causes an inconvenience in a tmux session: when I send text containing quotes to frome one pane (vim) to another pane (bash / python / R etc), every quote is turned into two, very annoying.
Is it possible to disable these lines in (and only in) tmux?

tmux sets the TMUX environment variable, so in .bashrc (or .profile or whatever):
if [ '' = "$TMUX" ] ; then
echo not in TMUX
else
echo in TMUX
fi
You can set INPUTRC to override the default .inputrc location, so you could have a tmux one and a non-tmux one, and export a suitable INPUTRC value in .bashrc depending on TMUX. You could even concoct a suitable .inputrc (e.g. in /tmp) for that session based on a "common" file and a "non-tmux session" file.
Unfortunately tmux exports TMUX, and so subshells started from a tmux session will have TMUX set regardless. Not found a way round that yet.

I ended up doing this in ~/.bashrc:
if [[ '' = "$TMUX" ]]
then
set -o vi
bind -m vi-insert '"(" "\C-v()\ei"'
bind -m vi-insert '"[" "\C-v[]\ei"'
bind -m vi-insert '"{" "\C-v{}\ei"'
bind -m vi-insert '"\"" "\C-v\"\C-v\"\ei"'
bind -m vi-insert '"\047" "\C-v\047\C-v\047\ei"'
else
echo Welcome to Tmux!
fi
UPDATE
Adopting user3392484 's suggestion, I found this much better:
if [[ '' = "$TMUX" ]]
then
export INPUTRC=~/.inputrc
else
export INPUTRC=~/.tmux.inputrc
echo Welcome to Tmux!
fi

Related

Adaptive Ruby version when opening a terminal

This question is the opposite of this one (also asked here, here and here)
I have two versions of ruby installed
ubuntu:~/environment $ rvm list
ruby-2.6.6 [ x86_64 ]
=* ruby-3.0.2 [ x86_64 ]
and every time I open a terminal window, ruby-3.0.2 (the default) is set. The problem is for a couple of my older projects I have to use ruby-2.6.6, so every time I have to switch with
rvm use 2.6.6
Is there a way to automatically select ruby 2.6.6 when I open the terminal window of the specific projects? I have tried to override the default rvm version with the .ruby-version file (as suggested here) but it does not do the trick.
EDIT File /home/ubuntu/.rvm/scripts/cd contains the following
#!/usr/bin/env bash
# Source a .rvmrc file in a directory after changing to it, if it exists. To
# disable this feature, set rvm_project_rvmrc=0 in /etc/rvmrc or $HOME/.rvmrc
case "${rvm_project_rvmrc:-1}" in
1|cd)
# cloned from git#github.com:mpapis/bash_zsh_support.git
source "$rvm_scripts_path/extras/bash_zsh_support/chpwd/function.sh"
# not using default loading to support older Zsh
[[ -n "${ZSH_VERSION:-}" ]] &&
__rvm_version_compare "$ZSH_VERSION" -gt 4.3.4 ||
{
function cd() { __zsh_like_cd cd "$#" ; }
function popd() { __zsh_like_cd popd "$#" ; }
function pushd() { __zsh_like_cd pushd "$#" ; }
}
__rvm_after_cd()
{
\typeset rvm_hook
rvm_hook="after_cd"
if [[ -n "${rvm_scripts_path:-}" || -n "${rvm_path:-}" ]]
then source "${rvm_scripts_path:-$rvm_path/scripts}/hook"
fi
}
__rvm_cd_functions_set()
{
__rvm_do_with_env_before
if [[ -n "${rvm_current_rvmrc:-""}" && "$OLDPWD" == "$PWD" ]]
then rvm_current_rvmrc=""
fi
__rvm_project_rvmrc >&2 || true
__rvm_after_cd || true
__rvm_do_with_env_after
return 0
}
[[ " ${chpwd_functions[*]} " == *" __rvm_cd_functions_set "* ]] ||
chpwd_functions=( "${chpwd_functions[#]}" __rvm_cd_functions_set )
# This functionality is opt-in by setting rvm_cd_complete_flag=1 in ~/.rvmrc
# Generic bash cd completion seems to work great for most, so this is only
# for those that have some issues with that.
if (( ${rvm_cd_complete_flag:-0} == 1 ))
then
# If $CDPATH is set, bash should tab-complete based on directories in those paths,
# but with the cd function above, the built-in tab-complete ignores $CDPATH. This
# function returns that functionality.
_rvm_cd_complete ()
{
\typeset directory current matches item index sep
sep="${IFS}"
export IFS
IFS=$'\n'
COMPREPLY=()
current="${COMP_WORDS[COMP_CWORD]}"
if [[ -n "$CDPATH" && ${current:0:1} != "/" ]] ; then
index=0
# The change to IFS above means that the \command \tr below should replace ':'
# with a newline rather than a space. A space would be ignored, breaking
# TAB completion based on CDPATH again
for directory in $(printf "%b" "$CDPATH" | \command \tr -s ':' '\n') ; do
for item in $( compgen -d "$directory/$current" ) ; do
COMPREPLY[index++]=${item#$directory/}
done
done
else
COMPREPLY=( $(compgen -d ${current}) )
fi
IFS="${sep}";
}
complete -o bashdefault -o default -o filenames -o dirnames -o nospace -F _rvm_cd_complete cd
fi
;;
2|prompt)
if
[[ -n "${ZSH_VERSION:-}" ]]
then
precmd_functions+=(__rvm_do_with_env_before __rvm_project_rvmrc __rvm_do_with_env_after)
else
PROMPT_COMMAND="${PROMPT_COMMAND%% }"
PROMPT_COMMAND="${PROMPT_COMMAND%%;}"
PROMPT_COMMAND="${PROMPT_COMMAND:-}${PROMPT_COMMAND:+; }__rvm_do_with_env_before; __rvm_project_rvmrc; __rvm_do_with_env_after"
fi
;;
esac
You are probably using RVM as a shell script, and not as a shell function.
You can check like this in a typical shell (bash, zsh, ...) : execute: type rvm
If it displays rvm is /home/ying/.rvm/bin/rvm : you are using as a script (found in $PATH)
If it displays rvm is a function : you are using as a function (much better).
Check out: https://rvm.io/rvm/basics#post-install-configuration
If you are using as a script, and want to use as a function: you need to "source" the rvm function, it is located in <rvm main folder>/scripts/rvm, for instance if installed in $HOME:
source $HOME/.rvm/scripts/rvm
source /usr/local/rvm/scripts/rvm
Typically, at RVM installation time, it add the following line in the equivalent of .profile (depending on shell and if its global or user):
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
RVM changes automatically the version as described here:
https://rvm.io/workflow/projects
For detection of .ruby-version, the following is required:
RVM must be a recent version that supports the feature
RVM must be loaded in the shell (typically by .profile, or equivalent) so that is is executed as a function
the shell must be compatible with this callback feature (bash and zsh are)
Here is what happens:
When you load rvm as a function, it registers callback in the shell
when you cd into the project, RVM callbacks (in shell) detect the file .ruby-version (or others) and automatically do the equivalent of rvm use.
For instance, I use zsh (on osx) which has preexec and precmd callbacks
and it detect the ruby version file and applies when I cd into it or a sub folder.
It works with bash too.
If you are curious or want to see why it does not work for you look at the file <rvm main dir>/scripts/cd
typically the shell variable chpwd_functions is set to __rvm_cd_functions_set
which is the function called after a cd by rvm

How to pass environment variables to docker container app user [duplicate]

When I use any command with sudo the environment variables are not there. For example after setting HTTP_PROXY the command wget works fine without sudo. However if I type sudo wget it says it can't bypass the proxy setting.
First you need to export HTTP_PROXY. Second, you need to read man sudo, and look at the -E flag. This works:
$ export HTTP_PROXY=foof
$ sudo -E bash -c 'echo $HTTP_PROXY'
Here is the quote from the man page:
-E, --preserve-env
Indicates to the security policy that the user wishes to preserve their
existing environment variables. The security policy may return an error
if the user does not have permission to preserve the environment.
The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:
Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"
taken from ArchLinux wiki.
For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:
Defaults env_keep += "http_proxy"
Defaults env_keep += "https_proxy"
Defaults env_keep += "HTTP_PROXY"
Defaults env_keep += "HTTPS_PROXY"
For individual variables you want to make available on a one off basis you can make it part of the command.
sudo http_proxy=$http_proxy wget "http://stackoverflow.com"
You can also combine the two env_keep statements in Ahmed Aswani's answer into a single statement like this:
Defaults env_keep += "http_proxy https_proxy"
You should also consider specifying env_keep for only a single command like this:
Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"
A simple wrapper function (or in-line for loop)
I came up with a unique solution because:
sudo -E "$#" was leaking variables that was causing problems for my command
sudo VAR1="$VAR1" ... VAR42="$VAR42" "$#" was long and ugly in my case
demo.sh
#!/bin/bash
function sudo_exports(){
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$#"
}
# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh
export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."
export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"
# clean function style
sudo_exports ./sudo_test.sh
# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh
Result
$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
How?
This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0
Add code snippets to /etc/sudoers.d
Don't know if this is available in all distros, but in Debian-based distros, there is a line at or near the tail of the /etc/sudoers file that includes the folder /etc/sudoers.d. Herein, one may add code "snippets" that modify sudo's configuration. Specifically, they allow control over all environment variables used in sudo.
As with /etc/sudoers, these "code snippets" should be edited using visudo. You can start by reading the README file, which is also a handy place for keeping any notes you care to make:
$ sudo visudo -f /etc/sudoers.d/README
# files for your snippets may be created/edited like so:
$ sudo visudo -f /etc/sudoers.d/20_mysnippets
Read the "Command Environment" section of 'man 5 sudoers'
Perhaps the most informative documentation on environment configuration in sudo is found in the Command environment section of man 5 sudoers. Here, we learn that a sudoers environment variables that are blocked by default may be "whitelisted" using the env_check or env_keep options; e.g.
Defaults env_keep += "http_proxy HTTP_PROXY"
Defaults env_keep += "https_proxy HTTPS_PROXY"
Defaults env_keep += "ftp_proxy FTP_PROXY"
And so, in the OP's case, we may "pass" the sudoer's environment variables as follows:
$ sudo visudo -f /etc/sudoers.d/10_myenvwlist
# opens the default editor for entry of the following lines:
Defaults env_keep += "http_proxy HTTP_PROXY"
Defaults env_keep += "https_proxy HTTPS_PROXY"
# and any others deemed useful/necessary
# Save the file, close the editor, and you are done!
Get your bearings from '# sudo -V'
The OP presumably discovered the missing environment variable in sudo by trial-and-error. However, it is possible to be proactive: A listing of all environment variables, and their allowed or denied status is available (and unique to each host) from the root prompt as follows:
# sudo -V
...
Environment variables to check for safety:
...
Environment variables to remove:
...
Environment variables to preserve:
...
Note that once an environment variable is "whitelisted" as above, it will appear in subsequent listings of sudo -V under the "preserve" listing.
If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.
# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Rails app does not read env variables in .bashrc

I have saved some ENV's in ~/.bashrc, I close and reopened the file and they are there for sure.
.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
. /etc/apache2/envvars
# If not running interactively, don't do anything else
[ -z "$PS1" ] && return
# 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
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# 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 [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
PS1='\[\033[01;32m\]${C9_USER}\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1 " (%s)") $ '
# 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
export rvm_silence_path_mismatch_check_flag=1
export TWILIO_SID="AXXXXX81b7eb5aXXXXeXXX6c9bfecX6X"
export TWILIO_TOKEN="XXX87XXXXXXe650ff2XXXXfXXXXX8X2"
export TWILIO_PHONE_NUMBER="+147043XXXX"
Yet when I tell my rails app to use them, for example use ENV["TWILIO_SID"] in my controller, it does not know them. I tried echoing them out in bash, it's just an empty line, in HTML, also empty line.
I am using c9 cloud IDE, and there is an option to manually enter ENV into the Rails shell, and when I do that, everything works fine. but my assignment asks for bashrc file... why are neither bash nor rails terminal reading my .bashrc? any help?
PS: the overall goal is to just set a UNIX env variable in my Rails app. I cannot use figaro.
PS2: Here is the code in controller where I'm using the variables. When I hard code them, everything works fine, so I know there is something going on with the env variables.
require 'twilio-ruby'
def index
end
class TexterController < ApplicationController
def index
end
def text
#number = params[:number]
#message = params[:message]
twilio_sid = ENV["TWILIO_SID"]
twilio_token = ENV["TWILIO_TOKEN"]
twilio_phone_number = ENV["TWILIO_PHONE_NUMBER"]
#client = Twilio::REST::Client.new(twilio_sid, twilio_token)
#message = #client.messages.create(
to: #number,
from: twilio_phone_number,
body: #message
)
render "pages/text.html.erb"
end
end
And here is the reasons why:
To change the environmental variable "permanently" you'll need to consider at least these situations:
Login/Non-login shell
Interactive/Non-interactive shell
Bash as login shell will load /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile in the order
Bash as non-login interactive shell will load ~/.bashrc
Bash as non-login non-interactive shell will load the configuration specified in environment variable $BASH_ENV
Source: how to permanently set environmental variables
Found it.
Turns out for some reason, even when I source .bashrc, the env variables are not read, but when I added them to .profile they are read and everything works fine.
Even tried adding them to .bashrc and then source ~/.bashrc to .profile, but still wouldn't work.

Is there a good macvim git diff?

I have been using textmate for many years and I just made the switch to macvim and one thing that I used all the time with textmate was the command git df which in my .gitconfig was just an alias for
[alias]
df = !git diff | mate
and what that did was give me a screen like this
Is there a replacement in mvim that I can add somewhere for me to get similar behavior
I describe what I use here.
Basically, add the following lines to your "~/.gitconfig":
[diff]
tool = default-difftool
[difftool "default-difftool"]
cmd = default-difftool.sh $LOCAL $REMOTE
With the following wrapper script:
#! /bin/bash
if [[ -f /Applications/MacVim.app/Contents/MacOS/Vim ]]
then
# bypass mvim for speed
VIMPATH='/Applications/MacVim.app/Contents/MacOS/Vim -g -dO -f'
elif [[ -f /usr/local/bin/mvim ]]
then
# fall back to mvim
VIMPATH='mvim -d -f'
else
# fall back to original vim
VIMPATH='vimdiff'
fi
$VIMPATH $#
You can get the diff one file at a time by doing:
git difftool -t vimdiff
vimdiff can be replaced with gvimdiff for gvim, so I would assume you can also replace it with mvimdiff for macvim.
I am not sure of a way to pipe the entirety of git diff into vim though.

How can I tell from a within a shell script if the shell that invoked it is an interactive shell?

I'm trying to set up a shell script that will start a screen session (or rejoin an existing one) only if it is invoked from an interactive shell. The solution I have seen is to check if $- contains the letter "i":
#!/bin/sh -e
echo "Testing interactivity..."
echo 'Current value of $- = '"$-"
if [ `echo \$- | grep -qs i` ]; then
echo interactive;
else
echo noninteractive;
fi
However, this fails, because the script is run by a new noninteractive shell, invoked as a result of the #!/bin/sh at the top. If I source the script instead of running it, it works as desired, but that's an ugly hack. I'd rather have it work when I run it.
So how can I test for interactivity within a script?
Give this a try and see if it does what you're looking for:
#!/bin/sh
if [ $_ != $0 ]
then
echo interactive;
else
echo noninteractive;
fi
The underscore ($_) expands to the absolute pathname used to invoke the script. The zero ($0) expands to the name of the script. If they're different then the script was invoked from an interactive shell. In Bash, subsequent expansion of $_ gives the expanded argument to the previous command (it might be a good idea to save the value of $_ in another variable in order to preserve it).
From man bash:
0 Expands to the name of the shell or shell script. This is set
at shell initialization. If bash is invoked with a file of com‐
mands, $0 is set to the name of that file. If bash is started
with the -c option, then $0 is set to the first argument after
the string to be executed, if one is present. Otherwise, it is
set to the file name used to invoke bash, as given by argument
zero.
_ At shell startup, set to the absolute pathname used to invoke
the shell or shell script being executed as passed in the envi‐
ronment or argument list. Subsequently, expands to the last
argument to the previous command, after expansion. Also set to
the full pathname used to invoke each command executed and
placed in the environment exported to that command. When check‐
ing mail, this parameter holds the name of the mail file cur‐
rently being checked.
$_ may not work in every POSIX compatible sh, although it probably works in must.
$PS1 will only be set if the shell is interactive. So this should work:
if [ -z "$PS1" ]; then
echo noninteractive
else
echo interactive
fi
try tty
if tty 2>&1 |grep not ; then echo "Not a tty"; else echo "a tty"; fi
man tty :
The tty utility writes the name of the terminal attached to standard
input to standard output. The name that is written is the string
returned by ttyname(3). If the standard input is not a terminal, the
message ``not a tty'' is written.
You could try using something like...
if [[ -t 0 ]]
then
echo "Interactive...say something!"
read line
echo $line
else
echo "Not Interactive"
fi
The "-t" switch in the test field checks if the file descriptor given matches a terminal (you could also do this to stop the program if the output was going to be printed to a terminal, for example). Here it checks if the standard in of the program matches a terminal.
Simple answer: don't run those commands inside ` ` or [ ].
There is no need for either of those constructs here.
Obviously I can't be sure what you expected
[ `echo \$- | grep -qs i` ]
to be testing, but I don't think it's testing what you think it's testing.
That code will do the following:
Run echo \$- | grep -qs i inside a subshell (due to the ` `).
Capture the subshell's standard output.
Replace the original ` ` expression with a string containing that output.
Pass that string as an argument to the [ command or built-in (depending on your shell).
Produce a successful return code from [ only if that string was nonempty (assuming the string didn't look like an option to [).
Some possible problems:
The -qs options to grep should cause it to produce no output, so I'd expect [ to be testing an empty string regardless of what $- looks like.
It's also possible that the backslash is escaping the dollar sign and causing a literal 'dollar minus' (rather than the contents of a variable) to be sent to grep.
On the other hand, if you removed the [ and backticks and instead said
if echo "$-" | grep -qs i ; then
then:
your current shell would expand "$-" with the value you want to test,
echo ... | would send that to grep on its standard input,
grep would return a successful return code when that input contained the letter i,
grep would print no output, due to the -qs flags, and
the if statement would use grep's return code to decide which branch to take.
Also:
no backticks would replace any commands with the output produced when they were run, and
no [ command would try to replace the return code of grep with some return code that it had tried to reconstruct by itself from the output produced by grep.
For more on how to use the if command, see this section of the excellent BashGuide.
If you want to test the value of $- without forking an external process (e.g. grep) then you can use the following technique:
if [ "${-%i*}" != "$-" ]
then
echo Interactive shell
else
echo Not an interactive shell
fi
This deletes any match for i* from the value of $- then checks to see if this made any difference.
(The ${parameter/from/to} construct (e.g. [ "${-//[!i]/}" = "i" ] is true iff interactive) can be used in Bash scripts but is not present in Dash, which is /bin/sh on Debian and Ubuntu systems.)

Resources