Linux Shell primer: Mastering Linux,os X,unix shell Environment _linux Shell

Source: Internet
Author: User
Tags aliases chmod memcached sessions ssh file permissions egrep

In Linux or Unix-like systems, each user and process is running in a specific environment. This environment contains variables, settings, aliases, functions, and more. Here is a brief introduction to some of the common commands in the shell environment, including examples of how each command is used, and setting your own environment at the command line to improve efficiency.

Find your current shell.

Enter any of the following commands in the terminal application:

PS $$
ps-p $$

Or

echo "$"

Output Example:

Figure 1: Finding the current shell

Find all installed shells

Locate the full path of the installed shell:

Type-a zsh
type-a ksh
type-a sh
type-a Bash

Output Example:

Figure 2: Finding the Shell's path

The file/etc/shells contains a list of the shell supported by the system. Each row represents a shell and is the complete path of the relative root directory. Use this cat command to view this data:

Cat/etc/shells

Output Example:

# List of acceptable shells for chpass (1).
# FTPD won't allow users to connect who are not using # One of these
shells.
 
/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh

Temporarily change the current shell

Just enter the name of the shell. In the following example, I switched from bash to zsh:

Zsh

This is just a temporary change to the system shell. Also called a child shell. To exit from the sub/Temp shell, enter the following command or press ctrl-d:

Exit

To find the level of a child shell or the nesting level of a temporary shell

After each instance of bash is started, the value of the variable $SHLVL will be added one. Enter the following command:

echo "$SHLVL"

Sample output:

Figure 3:bash Shell nesting level (number of child shells)

Permanently change the system shell with the CHSH command

Want to permanently change the current system shell from bash to zsh? Try this:

Chsh-s/bin/zsh

Want to permanently change the shell of another user from bash to Ksh? Try this:

sudo chsh-s/bin/ksh usernamehere

View the current environment variables

You need to use:

Env
ENV | more
env | less
env | grep ' NAME '

Sample output:

Term_program=apple_terminal
shell=/bin/bash
term=xterm-256color
tmpdir=/var/folders/6x/ 45252d6j1lqbtyy_xt62h40c0000gn/t/
Apple_pubsub_socket_render=/tmp/launch-djaojg/render
TERM_PROGRAM_ version=326
term_session_id=16f470e3-501c-498e-b315-d70e538da825
user=vivek
ssh_auth_sock=/tmp/ Launch-uqgj2h/listeners
__cf_user_text_encoding=0x1f5:0:0
path=/usr/bin:/bin:/usr/sbin:/sbin:/usr/ Local/bin:/opt/x11/bin:/usr/local/go/bin:/usr/local/sbin/modemzapp:/users/vivek/google-cloud-sdk/bin
__ Checkfix1436934=1
pwd=/users/vivek
shlvl=2
home=/users/vivek
logname=vivek
lc_ctype= UTF-8
display=/tmp/launch-6hnahh/org.macosforge.xquartz:0
_=/usr/bin/env
oldpwd=/users/vivek

Here is a list of some common variables in the bash shell:

Figure 4: Common Bash environment variables

Note : The following environment variables are all right, don't change. is likely to cause an unstable shell session:

SHELL

Uid

RANDOM

Pwd

PPID

SSHAUTHSock

USER

Home

Lineno

Display the value of an environment variable

Use any of the following commands to display the value of the environment variable home:

# # Use printenv #
printenv Home
 
# or with Echo # #
echo ' $HOME
 
# # Considering portability, you can also use printf # #
printf '%s\n ' $ Home "

Sample output:

/home/vivek

Add or set a new environment variable

The following are the syntax for Bash,zsh,sh and Ksh:

# # syntax # #
var=value
foo=bar
 
# set Vim as default text editor # #
editor=vim
Export $EDITOR
 
# # Consider security, Set default shell connection Timeout #
tmout=300
export tmout
 
# You can use the Export command to set the search path of the command. # #
Export path= $PATH: $ Home/bin:/usr/local/bin:/path/to/mycoolapps

Then, use the printenv or echo or printf commands to view the values of the environment variable path,editor, and tmout:

Printenv PATH
echo "$EDITOR"
printf "%s\n" $TMOUT

How to modify an existing environment variable?

Here's the syntax:

Export Var=value
# # or #
var=value
Export $VAR
 
# # Change the default text editor from Vim to Emacs #
Echo ' $EDITOR # # <--- Screen output vim
editor=emacs  # # <---modify
export $EDITOR # # <---Let the changes take effect in other sessions
echo "$EDITOR" # # <--- Screen output emacs 

The syntax for adding and modifying variables under the TCSH shell is as follows:

# # syntax
setenv var value
printenv var
 
# Set Variable Foo's value is bar # #
setenv foo bar
echo ' $foo '
printenv Foo
 
# # Set Variable path # #
setenv path $PATH \: $HOME/bin
echo "$PATH"
 
# # Set Variable pager # #
setenv PAGER most
printf "%s\n" $PAGER

Find the configuration file for the bash shell

Use the following command to list the files for the bash shell:

Ls-l ~/.bash* ~/.profile/etc/bash*/etc/profile

Sample output:

Figure 5: Listing all the profiles for bash

To view all bash profiles, enter:

Less ~/.bash* ~/.profile/etc/bash*/etc/profile

You can use a text editor such as Vim or Emacs to edit the bash profile one at a while:

Vim ~/.BASHRC

Edit the files in the/etc/directory and enter:

# # First is backup, just in case
sudo cp-v/etc/bashrc/etc/bashrc.bak.22_jan_15
 
############################################ ############################
# Then, arbitrarily change it, play the shell environment or improve the efficiency:         # #
############################# ###########################################
sudo vim/etc/bashrc

Confused by the files that were applied during the bash shell initialization?

The following "Bash initialization files" flowchart should help:

Depending on the default shell set by the account, your user configuration or system configuration may be one of the following:

Find zsh Shell configuration file

The following commands are recommended in Zsh's wiki:

Strings =zsh | grep ZSHRC

Sample output:

/ETC/ZSHRC
. ZSHRC

Enter the following command to list your zsh shell files:

Ls-l/etc/zsh/*/etc/profile ~/.z*

To view all zsh profiles:

less/etc/zsh/*/etc/profile ~/.z*

Find Ksh Shell configuration file

    1. View ~/.profile or/etc/profile files.

Find tcsh Shell configuration file

    1. C Shell View ~/.LOGIN,~/.CSHRC file.
    2. TC Shell view ~/.TCSHRC and ~/.CSHRC files.

Can I write a script like this to automatically execute every time I log on?

Yes, add your command or alias or other settings to the ~/.BASHRC (bash shell) or ~/.profile (Sh/ksh/bash) or ~/.login (csh/tcsh) file.

Can I write a script like this that automatically executes every time you log out?

Yes, add your command or alias or other settings to ~/.bash_logout (bash) or ~/.logout (csh/tcsh) files.

History: Get more information about shell sessions

Enter the history command to view the history of this session:

History

Sample output:

  9 ls
  VI advanced-cache.php one
  CD.
  LS
  w
  cd.
  LS
  pwd-
  ls
  ... ...
  HDDTEMP/DEV/SDA
  Yum Install hddtemp HDDTEMP/DEV/SDA-
  hddtemp/dev/sg0
  1
  smartctl-d ata-a/dev/sda temperature grep-i smartctl-d ata-a/dev/sg1 grep-i
  | temperature
  
   98 smartctl-a/DEV/SG1 | Grep-i Temperature
  Sensors

  

Enter History 20来 View the following 20 articles in the history of the command:

History 20

Sample output:

Figure 6: Viewing session history with the history command in the bash shell

You can reuse the previous commands. Simply press the [up] or [down] arrow keys to view the previous commands. Press [Ctrl-r] at the shell prompt to search the history cache or file backwards to find the command. Repeat the last command, just enter it at the shell prompt!! Just fine:

Ls-l/foo/bar
!!

Locate the command #93 (HDDTEMP/DEV/SDA) in the history above and enter:

!93

Use sudo or su to change users

Here's the syntax:

Su userName
 
# # Login for Tom user #
su Tom
 
# for user Tom Open a new shell session #
Su Tom
 
# # Sign in as root #
Su-
 
# # sudo command syntax (must be configured in the system with this command) # #
sudo-s
sudo tom

Read the post "Run command with other users under Linux" to learn more about the Sudo,su and Runuser commands.

Shell Alias

Aliases are just a shortcut to a command.

List all aliases

Enter the following command:

Alias

Sample output:

Alias.. = ' CD ... '
Alias ... = ' CD ... /.. /.. /'
alias ... = ' CD ... /.. /.. /.. /'
alias ... = ' CD. /.. /.. /.. /'
alias. 4= ' CD. /.. /.. /.. /'
alias. 5= ' CD. /.. /.. /.. /..'
Alias bc= ' Bc-l '
alias CD. = ' CD ... '
Alias chgrp= ' chgrp--preserve-root '
alias chmod= ' chmod--preserve-root '
alias chown= ' Chown--preserve-root '
alias cp= ' Cp-i '
alias dnstop= ' dnstop-l 5 eth1 '
alias egrep= ' egrep--color=auto '
alias ethtool= ' Ethtool eth1 '

Set an alias

BASH/ZSH Syntax:

Alias c= ' Clear '
alias down= ' Sudo/sbin/shutdown-h now '

For command clear, you can enter a C alias so that we can empty the screen by entering C instead of the clean command:

C

or enter down to shut down the Linux based server:

Down

You can set any number of aliases. Look at the "30 handy bash shell aliases in the Linux/unix/mac OS x system" to understand the actual application of aliases in Unix-like systems.

Shell functions

The BASH/KSH/ZSH function allows you to further configure the shell environment. In this example, I wrote a simple bash function called MEMCPU () to show the top 10 CPU and memory processes:

Memcpu () {echo "* * * * TOP CPU EATING Process * * * PS auxf | sort-nr-k 3 | head-10;
echo "* * * top Memory eating process * * *; PS AUXF | Sort-nr-k 4 | head-10; }

Enter MEMCPU to see the following information on the screen:

MEMCPU * * * Top CPU EATING Process * * * nginx 39559 13.0 0.2 264020 35168?    S 04:26 0:00 \_/usr/bin/php-cgi nginx 39545 6.6 0.1 216484 13088?    S 04:25 0:04 \_/usr/bin/php-cgi nginx 39471 6.2 0.6 273352 81704?    S 04:22 0:17 \_/usr/bin/php-cgi nginx 39544 5.7 0.1 216484 13084?    S 04:25 0:03 \_/usr/bin/php-cgi nginx 39540 5.5 0.1 221260 19296?    S 04:25 0:04 \_/usr/bin/php-cgi nginx 39542 5.4 0.1 216484 13152?    S 04:25 0:04 \_/usr/bin/php-cgi nixcraft 39543 5.3 0.1 216484 14096?    S 04:25 0:04 \_/usr/bin/php-cgi nixcraft 39538 5.2 0.1 221248 18608?    S 04:25 0:04 \_/usr/bin/php-cgi nixcraft 39539 5.0 0.1 216484 16272?    S 04:25 0:04 \_/usr/bin/php-cgi nixcraft 39541 4.8 0.1 216484 14860?   S 04:25 0:04 \_/usr/bin/php-cgi * * * top Memory eating Process * * * 498 63859 0.5 4.0 2429652 488084? SSL 2014 177:41 memcached-d-P 11211-u memcached-m 2048-c 18288-p/var/run/memcached/memcached.pid-l 10.10.29.68-l MySQL 64221 4.2 3.4 4653600 419868? Sl 2014 1360:40 \_/usr/libexec/mysqld--basedir=/usr--datadir=/var/lib/mysql--user=mysql--log-error=/var/log/
Mysqld.log--open-files-limit=65535--pid-file=/var/run/mysqld/mysqld.pid--socket=/var/lib/mysql/mysql.sock    Nixcraft 39418 0.4 1.1 295312 138624?  S 04:17 0:02 |    \_/usr/bin/php-cgi nixcraft 39419 0.5 0.9 290284 113036?  S 04:18 0:02 |    \_/usr/bin/php-cgi nixcraft 39464 0.7 0.8 294356 99200?  S 04:20 0:02 |    \_/usr/bin/php-cgi nixcraft 39469 0.3 0.7 288400 91256?  S 04:20 0:01 |    \_/usr/bin/php-cgi nixcraft 39471 6.2 0.6 273352 81704?    S 04:22 0:17 \_/usr/bin/php-cgi Vivek 39261 2.2 0.6 253172 82812?    S 04:05 0:28 \_/usr/bin/php-cgi squid 9995 0.0 0.5 175152 72396?    S 2014 27:00 \_ (squid)-f/etc/squid/squid.conf cybercit 3922 0.0 0.4 303380 56304?  S Jan10 0:13 |
 \_/usr/bin/php-cgi

See "How to write and apply shell functions" for more information.

In combination: Customize your own Linux or UNIX bash shell work environment

Now, you will use the Bash shell to configure your environment. I'll just introduce bash. But theoretically zsh,ksh is about the same as any other common shell. Let's see how to adjust the shell to suit my requirements as a system administrator. Edit your ~/.BASHRC file to attach the settings. Here are some common configuration options.

#1: Set bash path and environment variables

# set PATH # #
export path= $PATH:/usr/local/bin:/home/vivek/bin:/opt/firefox/bin:/opt/oraapp/bin
 
# set path for CD command
export cdpath=.: $HOME:/var/www

Use the less or more command as a page-picker:

Export pager=less

Set VIM as the default text editor:

Export Editor=vim
export visual=vim
export svn_editor= "$VISUAL"

Set parameters specifically required for Oracle databases:

Export oracle_home=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export oracle_sid=xe
export NLS_ lang=$ ($ORACLE _home/bin/nls_lang.sh)

Set Java_home and other Java paths, such as the Java version:

Export JAVA_HOME=/USR/LIB/JVM/JAVA-6-SUN/JRE
 
# Add ORACLE and JAVA to the PATH
export path= $PATH: $ORACLE _home/bin:$ Java_home/bin

Use a key to achieve password-free logon to make SSH telnet more secure:

# There's no need to lose the code
/usr/bin/keychain $HOME/.ssh/id_rsa
source $HOME/.keychain/$HOSTNAME-sh

Finally, open the Bash command to be padded

Source/etc/bash_completion

#2: Set bash command prompt

To set a custom bash prompt (PS1):

Ps1= ' {\u@\h:\w}\$ '

#3: Set Default file Permissions

# # Set default permissions for 644 # #
Umask 022

#4: Adjust shell command history settings

# do not write to the same line in command history
histcontrol=ignoreboth
 
# Ignore these commands
histignore= ' reboot:shutdown *:ls:pwd:exit:mount:man *: History "
 
# Set the length of the command history through Histsize and histfilesize
export histsize=10000
export histfilesize=10000
 
# Add timestamp to command history file
export histtimeformat= "%F%T"
 
# Append to command history file, not overwrite
shopt-s histappend

#5: Setting the time zone for the shell session

# # Set ist for my own shell session (India Standard Time) # #
Tz=asia/kolkata

#6: Set Shell line Edit interface

# # Use the vi-style line editing interface, instead of bash default emacs mode # #
Set-o VI

#7: Set the alias of your preference

# # Add some protection # #
alias rm= ' Rm-i '
alias cp= ' Cp-i '
alias mv= ' Mv-i '
 
# # Memcached # #
alias mcdstats= '/usr/ Bin/memcached-tool 10.10.29.68:11211 Stats '
alias mcdshow= '/usr/bin/memcached-tool 10.10.29.68:11211 display '
alias mcdflush= ' echo ' flush_all | nc 10.10.29.68 11211 '
 
# # default command Parameters # #
alias vi= ' vim '
alias grep= ' grep- -color=auto '
alias egrep= ' egrep--color=auto '
alias fgrep= ' Fgrep--color=auto '
alias bc= ' Bc-l
' Alias wget= ' Wget-c '
alias chown= ' chown--preserve-root '
alias chmod= ' chmod--preserve-root '
alias chgrp= ' chgrp--preserve-root '
alias rm= ' rm-i--preserve-root '
alias ln= ' Ln-i '

Here are some additional OS X Unix bash shell aliases:

# from Bash Open desktop application
alias preview= "Open-a ' $PREVIEW" "
alias safari=" Open-a Safari "
alias firefox=" Open-a Firefox "
alias chrome=" Open-a google\ Chrome "
alias f= ' open-a Finder '"
 
cleans those. Ds_store file
alias dsclean= ' Find.-type f-name. Ds_store-delete '

#8: I Lust

# color grep output 
alias grep= ' grep--color=auto '
export grep_color= ' 1;33 '
 
# color LS
export lscolors= ' Gxfxcxdxdxegedabagacad '
# gnu/linux ls
ls= ' ls--color=auto '
 
# bsd/os x's ls command
# alias ls= ' Ls-g '

#9: Bash function to set your preferences

# Displays 10 recent history commands on the screen function ht {history | awk ' {a[$2]++}end{for (i in a) {print a[i] "I}" | Sort-rn | Replace # Host and ping command # accept the http://or https://or ftps://name as the domain or host name _getdomainnameonly () {local h= ' "", f=, "# Remove protocol part of hostname f=" ${f#http://} "f=" ${f#https://} "f=" ${f#ftp://} "f=" ${f#scp://} "f = "${f#scp://}" f= "${f#sftp://}" # Remove username and/or Username:password part of hostname f= ' ${f#*:* @} ' f= ' ${f#*     @} "# remove all/foo/xyz.html* f=${f%%/*} # Show domain name only echo ' $f '} ping () {local array= ($@)  # get all args in a array local len=${#array [@]} # Find the length of a array local host=${array[$len-1]} # Get the ' last arg ' local args=${array[@]:0: $len-1} # get all args before ' last arg in $@ in ' array local _ping= '/ Bin/ping "Local c=$" (_getdomainnameonly "$host") ["$t"!= "$c"] && echo "sending ICMP echo_request to \" $c \ ".
  .." # Pass args and host $_ping $aRGS $c} host () {local array= ($@) Local len=${#array [@]} local host=${array[$len-1]} local args=${array[@]:0:$ len-1} local _host= "/usr/bin/host" local c=$ (_getdomainnameonly "$host") ["$t"!= "$c"] && echo "performin
 G DNS lookups for \ "$c \" ... "$_host $args $c}

#10: Set bash shell behavior via Shell shopt command

Finally, you can use the set and SHOPT commands to adjust the bash shell environment:

# Catalog spelling correction
shopt-q-S Cdspell
 
# ensures that the display SHOPT-Q-S checkwinsize is updated each time the terminal window is resized to
 
open the Advanced mode matching feature
Shopt-q-S EX Tglob
 
# Append command history instead of overlay
shopt-s histappend
 
# in command history use multiline
Shopt-q-S Cmdhist
 
# notify
immediately at the end of a background task Set-o notify
 
# Disables [ctrl-d] to end shell
Set-o ignoreeof

Summarize

This post is not difficult to understand. It briefly introduces how to customize the user environment from scratch. To get an insight into bash/ksh/zsh/csh/tcsh/'s capabilities, I suggest you read the man document with the following command:

Man bash
Mans zsh man
tcsh
Mans Ksh

This article was contributed by Aadrika, edited by admin and added additional content. You can also make a contribution to Nixcraft.

via:http://www.cyberciti.biz/howto/shell-primer-configuring-your-linux-unix-osx-environment/

Author: nixcraft Translator: zpl1025 proofreading: Wxy

This article is originally translated by Lctt

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.