How do I add a new path to $PATH variable under Linux and UNIX like operating system? What is my path, and how do I set or modify it using csh/tcsh or bash/ksh/sh shell?
The PATH is an environment variable. It is a colon delimited list of directories that your shell searches through when you enter a command. All executables are kept in different directories on the Linux and Unix like operating systems. Tutorial details
Difficulty Easy (rss) Root privileges No Requirements None Estimated completion time 5m Finding out your current path To find out what your current path setting, type the following command at shell prompt. Open the Terminal and then enter:
echo "$PATH"
OR
printf "%s\n" "$PATH"
Sample outputs: /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/sbin/mod emZapp:/Users/vivek/gcutil-1.8.4 How do I modify my path? To modify your path edit $PATH variable as per your shell. The syntax for setting path under UNIX / Linux dependent upon your login shell. Bash, Sh, Ksh shell syntax to modify $PATH If you are using bash, sh, or ksh, at the shell prompt, type: ## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ## export PATH=$PATH:/path/to/dir1 export PATH=$PATH:/path/to/dir1:/path/to/dir2
OR ## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ## PATH=$PATH:/path/to/dir1; export PATH
Please feel free to replace /path/to/dir1 with the directory you want the shell to search. Tcsh or csh shell syntax to modify $PATH If you are using tcsh or csh, shell enter: ## please note 'path' is case sensitivity and must be in lowercase ## set path = ($path /path/to/dir1) set path = ($path /path/to/dir1 /path/to/dir2)
OR ## please note 'PATH' is CASE sensitivity and must be in UPPERCASE ## setenv PATH $PATH:/path/to/dir1 setenv PATH $PATH:/path/to/dir1:/path/to/dir2
Please feel free to replace /path/to/dir1 with the directory you want the shell to search. Examples In this example add /usr/local/bin to your path under BASH/ksh/sh shell, enter:
export PATH=$PATH:/usr/local/bin
OR
PATH=$PATH:/usr/local/bin; export PATH
To make these changes permanent, add the commands described above to the end of your ~/.profile file for sh and ksh shell, or ~/.bash_profile file for bash shell: ## BASH SHELL ## echo 'export PATH=$PATH:/usr/local/bin' >> ~/.bash_profile
KSH/sh shell user try: ## KSH / SH SHELL ## echo 'export PATH=$PATH:/usr/local/bin' >> ~/.profile
In this final example add /usr/local/bin/ and /scripts/admin/ to your path under csh / tcsh shell, enter:
set path = ($path /usr/local/bin /scripts/admin)
OR
setenv PATH $PATH:/usr/local/bin:/scripts/admin
To make these changes permanent, add the commands described above to the end of your ~/.cshrc file:
To verify new path settings, enter: $ echo $PATH Environment variables Jump to: navigation, search An environment variable is a named object that contains data used by one or more applications. In simple terms, it is a variable with a name and a value. The value of an environmental variable can for example be the location of all executable files in the file system, the default editor that should be used, or the system locale settings. Users new to Linux may often find this way of managing settings a bit unmanageable. However, environment variables provides a simple way to share configuration settings between multiple applications and processes in Linux. Contents 1 Utilities 2 Examples 3 Defining variables o 3.1 Globally o 3.2 Per user 3.2.1 Graphical applications o 3.3 Per session 4 See also Utilities The coreutils package contains the programs printenv and env. To list the current environmental variables, use printenv to print the names and the values of each. Note: Some environment variables are user-specific. Check by comparing the outputs of printenv as an unprivileged user and as root. $ printenv The env utility can be used to run a command under a modified environment. The following example will launch xterm with the environment variable EDITOR set to vim. This will not affect the global environment variable EDITOR. $ env EDITOR=vim xterm The Bash builtin set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables. For more information, see the set documentation: [1]. To see what environment variables are available to a specific process, look in /proc/${PID}/environ. This file contains special \x0 characters. You can parse it with this function. # envof() { sudo sed 's/\x0/\n/g' /proc/${1}/environ; } # envof 1 TERM=linux Examples The following section lists a number of common environment variables used by a Linux system and describes their values. DE indicate the Desktop Environment being used. xdg-open will use it to chose more user- friendly file-opener application that desktop environment provides. Some packages need to be installed to use this feature. For GNOME, that would be libgnome. For Xfce, exo. Recognised values of DE variable are: gnome, kde, xfce, lxde and mate. The DE environment variable needs to be exported before starting the window manager. For example: ~/.xinitrc export DE="xfce" exec openbox This will make xdg-open use the more user-friendly exo-open, because it assumes it is inside Xfce. Use exo-preferred-applications for configuring. DESKTOP_SESSION. In LXDE desktop enviroment, when DESKTOP_SESSION is set to LXDE, xdg- open will use pcmanfm file associations. PATH Contains a colon-separated list of directories in which your system looks for executable files. When a regular command (e.g., ls, rc-update or emerge) is interpreted by the shell (e.g., bash, zsh), the shell looks for an executable file with same name as your command in the listed directories, and executes it. To run executables that are not listed in PATH, the absoute path to the executable must be given: /bin/ls. Note: It is advised not to include the current working directory (.) into your PATH for security reasons, as it may trick the user to execute vicious commands. HOME Contains the path to the home directory of the current user. This variable can be used by applications to associate configuration files and such like with the user running it. PWD Contains the path to your working directory. OLDPWD Contains the path to your previous working directory, that is, the value of PWD before last cd was executed. SHELL Contains the name of the running, interactive shell, e.g., bash TERM Contains the name of the running terminal, e.g., xterm PAGER Contains the path to the program used to list the contents of files, e.g., /bin/less. EDITOR Contains the path to the lightweight program used for editing files, e.g., /usr/bin/nano, or an interactive switch (between gedit under X or nano in this example): export EDITOR="$(if [[ -n $DISPLAY ]]; then echo 'gedit'; else echo 'nano'; fi)" VISUAL Contains the path to full-fledged editor that is used for more demanding tasks, such as editing mail; e.g., vi, vim, emacs, etc. MAIL Contains the location of incoming email. The traditional setting is /var/spool/mail/$LOGNAME. BROWSER Contains the path to the web browser. Helpful to set in an interactive shell configuration file so that it may be dynamically altered depending on the availability of a graphic environment, such as X: if [ -n "$DISPLAY" ]; then export BROWSER=firefox else export BROWSER=links fi ftp_proxy and http_proxy Contains FTP and HTTP proxy server, respectively: ftp_proxy="ftp://192.168.0.1:21" http_proxy="http://192.168.0.1:80" MANPATH Contains a colon-separated list of directories in which man searches for the man pages. Note: In /etc/profile, there is a comment that states "Man is much better than us at figuring this out", so this variable should generally be left as default, i.e. /usr/share/man:/usr/local/share/man INFODIR Contains a colon-separated list of directories in which the info command searches for the info pages, e.g., /usr/share/info:/usr/local/share/info TZ can be used to to set a time zone different to the system zone for a user. The zones listed in /usr/share/zoneinfo/ can be used as reference, for example TZ="usr/share/zoneinfo/Pacific/Fiji" Defining variables See also Systemd/User#Environment variables. Globally Most Linux distributions tell you to change or add environment variable definitions in /etc/profile or other locations. Be sure to maintain and manage the environment variables and pay attention to the numerous files that can contain environment variables. In principle, any shell script can be used for initializing environmental variables, but following traditional UNIX conventions, these statements should be only be present in some particular files. The following files should be used for defining global environment variables on your system: /etc/profile, /etc/bash.bashrc and /etc/environment. An example that sets all users ~/bin in their respective path, put this in your preferred global environment variable config file: # If user ID is greater than or equal to 1000 & if ~/bin exists and is a directory & if ~/bin is not already in your $PATH # then export ~/bin to your $PATH. if [[ $UID -ge 1000 && -d $HOME/bin && -z $(echo $PATH | grep -o $HOME/bin) ]] then export PATH=$HOME/bin:${PATH} fi Per user You do not always want to define an environment variable globally. For instance, you might want to add /home/my_user/bin to the PATH variable but do not want all other users on your system to have that in their PATH too. The following files should be used for local environment variables on your system: ~/.bashrc, ~/.profile, ~/.bash_login and ~/.bash_logout. To add a directory to PATH for local usage, put following in ~/.bash_profile: export PATH="${PATH}:/home/my_user/bin" To update the variable, re-login or source the file: $ source ~/.bash_profile. Graphical applications To set environment variables for GUI applications, you can put your variables in xinitrc, for example: ~/.xinitrc export PATH="${PATH}:~/scripts" export GUIVAR=value
In this article we would understand linux environment variables. Environmental variable plays significant role in linux system. We would cover following topics in this article What is a linux environment variable How to show linux environment variable How to set linux environment variable How to set linux environmental variable permanently List of Linux environmental variable What is a linux environment variable Linux environment variable is an object that contains value. In simple terms it is a pair of data object and their respective values. If you are familiar with programming language than you can easily understand it. Linux environment variables do same job which variables do in programming language. If you are not familiar with programming language you can understand linux variable as a container with name which keeps value inside it. This value could be location of all executable files in the filesystem, the default editor that should be used, or the system locale settings. Example of linux environmental variable Let take a simple example of ls command to understand linux environmental variables. ls the basic command to list the content of directory. When execute a command in linux, you need to type the full path of that command. Since the ls command is in the /bin directory, users should execute the /bin/ls command to list files in the current directory. Here comes the magic of linux environmental variables. Linux have a PATH variable. With the help of the PATH variable, full path is not required. The bash shell automatically searches through the directories listed in a user's PATH variable for the command that user just typed at the command line. When a matching command found shell run it. In this way environment variable provides a simple way to share configuration settings between multiple applications and processes in Linux. How to show linux environment variable printenv or env command can be use to list linux environment variables. The coreutils package contains printenv and env. Use printenv command to show linux environmental variables. $ printenv
The env utility can also be used to show linux environment variables. $env
printenv to print the names and the values of each. Note that some environment variables are user-specific. Output of env and printenv are too big to fit in screen. We can redirect the output of printenv in a file. To redirect the output of printenv in a file run following command $printenv > tmp_file
now we can read the tmp_file with less command. $less tmp_file
Use up arrow and down arrow key to scroll. Press q to exist from file
After reading you can simple remove the temporary file $rm tmp_file
How to set linux environment variable Linux environment can be set in three ways. Temporary also know as Session Specific Variables permanent locally Permanent globally To set linux environmental variable temporary use export command. PATH variable contains location of executable files. To check current PATH use following command $ echo $PATH
Now we would add our directory in this path. Make a directory $makdir custom_script To add this directory in path run following commands $export PATH="${PATH}:/home/user1/custom_script" Verify that we have successfully added our custom_script directory in PATH variable
Now move in our custom_script directory and make a sample script
make sample_script executable and run script directly from command prompt.
You can also verify that shell run sample_script from our custom_script directory by which command
Temporary variable only available in current session. To test it log out from current user and login back. Run sample_script again. This time you will get command not found error.
How to set linux environmental variable permanently Defining Variables Locally As you seen temporary variables are available only on that session. We can make those variables permanent. For security reason you should not define an environment variable globally unless you have sound understanding of linux system. For instance, you might want to add /home/user_name/custom_script to the PATH variable for a particular user. In such a case define it locally. As you do not want all other users on your system to have that in their PATH too. The following files should be used for local environment variables on your system: ~/. profile, ~/.bash_profile, ~/.bash_login and ~/.bash_logout.
To add our custom_script directory in to the PATH variable for local usage open .bash_profile file vi ~/.bash_profile
add our directory /home/user1/custom_script in PATH variable
To update the variable, re-login required. Logout
Login back Now check that our custom path is available
Permanently set linux environmental variable Globally root privilege requires to set linux environment variable globally. RHEL maintain and manage the environment variables in numerous files. But you do not need to pay attentions on all files that can contain environment variables. Following the RHEL recommendation you should only set environmental variables in some particular files. The following files should be used for defining global environment variables on your system: /etc/profile, /etc/bash.bashrc and /etc/environment. /etc/profile.d Directory is used to define global script. Login from root and move to /etc
move to /etc/profile.d directory Make a simple test script and make this script executable
This script print a simple welcome message for all users To test it logout from root and login back from normal user
We have successfully added global script. After testing to remove it login back from root remove our test script
List of Linux environmental variable Variable name Stored information DISPLAY used by the X Window system to identify the display server DOMAIN domain name EDITOR stores your favorite line editor HISTSIZE size of the shell history file in number of lines HOME path to your home directory HOSTNAME local host name INPUTRC location of definition file for input devices such as keyboard LANG preferred language LD_LIBRARY_PATH paths to search for libraries LOGNAME login name MAIL location of your incoming mail folder MANPATH paths to search for man pages OS string describing the operating system OSTYPE more information about version etc. PAGER used by programs like man which need to know what to do in case output is more than one terminal window. PATH search paths for commands PS1 primary prompt PS2 secondary prompt PWD present working directory SHELL current shell TERM terminal type UID user ID USER(NAME) user name VISUAL your favorite full-screen editor XENVIRONMENT location of your personal settings for X behavior XFILESEARCHPATH paths to search for graphical libraries his way: export PATH=~/opt/bin:$PATH or this? export PATH=$PATH:~/opt/bin Question 2 (related). What's a workable way to append more paths on different lines? Initially I thought this could do the trick: export PATH=$PATH:~/opt/bin export PATH=$PATH:~/opt/node/bin but it doesn't because the second assignment doesn't only append ~/opt/node/bin, but also the whole PATH previously assigned. This is a possible workaround: export PATH=$PATH:~/opt/bin:~/opt/node/bin but for readability I'd prefer to have one assignment for one path. bash environment-variables path bashrc shareimprove this question edited Jul 24 at 12:31
terdon 35.4k438104 asked Dec 4 '11 at 20:57
Guandalino 9362920
5
+1 Very useful question! Noldorin Jul 16 '12 at 1:16 add a comment 4 Answers active oldest votes up vote 105 down vote accepted The simple stuff PATH=$PATH:~/opt/bin PATH=~/opt/bin:$PATH depending on whether you want to add ~/opt/bin at the end (to be searched after all other directories, in case there is a program by the same name in multiple directories) or at the beginning (to be searched before all other directories). You can add multiple entries at the same time. PATH=$PATH:~/opt/bin:~/opt/node/bin or variations on the ordering work just fine. You don't need export if the variable is already in the environment: any change of the value of the variable is reflected in the environment. PATH is pretty much always in the environment; all unix systems set it very early on (usually in the very first process, in fact). If your PATH gets built in a by many different components, you might end up with duplicate entries. See How to add home directory path to be discovered by Unix which command? and Remove duplicate $PATH entries with awk command to avoid adding duplicates or remove them. Where to put it Note that ~/.bash_rc is not read by any program, and ~/.bashrc is the configuration file of interactive instances of bash. You should not define environment variables in ~/.bashrc. The right place to define environment variables such as PATH is ~/.profile (or ~/.bash_profile if you don't care about shells other than bash). See What's the difference between them and which one should I use? Notes on shells other than bash In bash, ksh and zsh, export is special syntax, and both PATH=~/opt/bin:$PATH and export PATH=~/opt/bin:$PATH do the right thing even. In other Bourne/POSIX-style shells such as dash (which is /bin/sh on many systems), export is parsed as an ordinary command, which implies two differences: ~ is only parsed at the beginning of a word, except in assignments (see How to add home directory path to be discovered by Unix which command? for details); $PATH outside double quotes breaks if PATH contains whitespace or \[*?. So in shells like dash, export PATH=~/opt/bin:$PATH sets PATH to the literal string ~/opt/bin/: followed by the value of PATH up to the first space. PATH=~/opt/bin:$PATH (a bare assignment) doesn't require quotes and does the right thing. If you want to use export in a portable script, you need to write export PATH="$HOME/opt/bin:$PATH".
This wasn't true in Bourne shells (as in the actual Bourne shell, not modern POSIX-style shells), but you're highly unlikely to encounter such old shells these days.
shareimprove this answer edited Jun 25 at 8:25 answered Dec 4 '11 at 23:39
Gilles 216k27301603
In exactly which shell does export var=~ not get expanded? Certainly this is not the case in bash which is the specifically tagged shell in the question. mikeserv Jun 23 at 1:29 add a comment
up vote 24 down vote Either way works, but they don't do the same thing: the elements of PATHare checked left to right. In your first example, executables in ~/opt/bin will have precedence over those installed, for example, in /usr/bin, which may or may not be what you want. In particular, from a safety point of view, it is dangerous to add paths to the front, because if someone can gain write access to your ~/opt/bin, they can put, for example, a different ls in there, which you'd then probably use instead of /bin/ls without noticing. Now imagine the same for ssh or your browser or choice... (The same goes triply for putting . in your path.) shareimprove this answer answered Dec 4 '11 at 21:09
Ulrich Schwarz 3,5441827
add a comment up vote 6 dow Guandalino, I'm confused by question 2. If you say n vote PATH=~/opt/bin that's all that will be in your PATH. PATH is just an environment variable, and if you want to add to the PATH, you have to rebuild the variable with exactly the contents you want. That is, what you give as an example to question 2 is exactly what you want to do, unless I'm totally missing the point of the question. I use both forms in my code. I have a generic profile that I install on every machine I work on that looks like this, to accommodate for potentially-missing directories: export PATH=/opt/bin:/usr/local/bin:/usr/contrib/bin:/bin:/usr/bin:/usr/sbin:/us r/bin/X11 # add optional items to the path for bindir in $HOME/local/bin $HOME/bin; do if [ -d $bindir ]; then PATH=$PATH:${bindir} fi done shareimprove this answer answered Dec 5 '11 at 0:25
Carl Cravens 25613
2
You are right about the example of question 2, it works. Another PATH related issue on my system confused me. Sorry for that. Guandalino Dec 5 '11 at 0:59 add a comment up vote 5 down vote Linux determines the executable search path with the $PATH environment variable. To add directory /data/myscripts to the beginning of the $PATH environment variable, use the following: PATH=/data/myscripts:$PATH To add that directory to the end of the path, use the following command: PATH=$PATH:/data/myscripts But the preceding are not sufficient because when you set an environment variable inside a script, that change is effective only within the script. There are only two ways around this limitation: If, within the script, you export the environment variable it is effective within any programs called by the script. Note that it is not effective within the program that called the script. If the program that calls the script does so by inclusion instead of calling, any environment changes in the script are effective within the calling program. Such inclusion can be done with the dot command or the source command. Examples: $HOME/myscript.sh source $HOME/myscript.sh Inclusion basically incorporates the "called" script in the "calling" script. It's like a #include in C. So it's effective inside the "calling" script or program. But of course, it's not effective in any programs or scripts called by the calling program. To make it effective all the way down the call chain, you must follow the setting of the environment variable with an export command. As an example, the bash shell program incorporates the contents of file .bash_profile by inclusion. So putting the following 2 lines in .bash_profile: PATH=$PATH:/data/myscripts export PATH effectively puts those 2 lines of code in the bash program. So within bash the $PATH variable includes $HOME/myscript.sh, and because of the export statement, any programs called by bash have the altered $PATH variable. And because any programs you run from a bash prompt are called by bash, the new path is in force for anything you run from the bash prompt. The bottom line is that to add a new directory to the path, you must append or prepend the directory to the $PATH environment variable within a script included in the shell, and you must export the $PATH environment variable.
An important Unix concept is the environment, which is defined by environment variables. Some are set by the system, others by you, yet others by the shell, or any program that loads another program. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. For example, first we set a variables TEST and then we access its value using echo command: $TEST="Unix Programming" $echo $TEST Unix Programming Note that environment variables are set without using $ sign but while accessing them we use $sign as prefix. These variables retain their values until we come out shell. When you login to the system, the shell undergoes a phase called initialization to set up various environment. This is usually a two step process that involves the shell reading the following files: /etc/profile profile The process is as follows: 1. The shell checks to see whether the file /etc/profile exists. 2. If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed. 3. The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in. 4. If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed. As soon as both of these files have been read, the shell displays a prompt: $ This is the prompt where you can enter commands in order to have them execute. Note - The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used by bash and ksh. The .profile File: The file /etc/profile is maintained by the system administrator of your UNIX machine and contains shell initialization information required by all users on a system. The file .profile is under your control. You can add as much shell customization information as you want to this file. The minimum set of information that you need to configure includes The type of terminal you are using A list of directories in which to locate commands A list of variables effecting look and feel of your terminal. You can check your .profile available in your home directory. Open it using vi editor and check all the variables set for your environment. Setting the Terminal Type: Usually the type of terminal you are using is automatically configured by either the login or getty programs. Sometimes, the autoconfiguration process guesses your terminal incorrectly. If your terminal is set incorrectly, the output of commands might look strange, or you might not be able to interact with the shell properly. To make sure that this is not the case, most users set their terminal to the lowest common denominator as follows: $TERM=vt100 $ Setting the PATH: When you type any command on command prompt, the shell has to locate the command before it can be executed. The PATH variable specifies the locations in which the shell should look for commands. Usually it is set as follows: $PATH=/bin:/usr/bin $ Here each of the individual entries separated by the colon character, :, are directories. If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, a message similar to the following appears: $hello hello: not found $ There are variables like PS1 and PS2 which are discussed in the next section. PS1 and PS2 Variables: The characters that the shell displays as your command prompt are stored in the variable PS1. You can change this variable to be anything you want. As soon as you change it, it'll be used by the shell from that point on. For example, if you issued the command: $PS1='=>' => => => Your prompt would become =>. To set the value of PS1 so that it shows the working directory, issue the command: =>PS1="[\u@\h \w]\$" [root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$ [root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$ The result of this command is that the prompt displays the user's username, the machine's name (hostname), and the working directory. There are quite a few escape sequences that can be used as value arguments for PS1; try to limit yourself to the most critical so that the prompt does not overwhelm you with information. Escape Sequence Description \t Current time, expressed as HH:MM:SS. \d Current date, expressed as Weekday Month Date \n Newline. \s Current shell environment. \W Working directory. \w Full path of the working directory. \u Current user.s username. \h Hostname of the current machine. \# Command number of the current command. Increases with each new command entered. \$ If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $. You can make the change yourself every time you log in, or you can have the change made automatically in PS1 by adding it to your .profile file. When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enter again. The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable: Following is the example which uses the default secondary prompt: $ echo "this is a > test" this is a test $ Following is the example which re-define PS2 with a customized prompt: $ PS2="secondary prompt->" $ echo "this is a secondary prompt->test" this is a test $ Environment Variables: Following is the partial list of important environment variables. These variables would be set and accessed as mentioned above: Variable Description DISPLAY Contains the identifier for the display that X11 programs should use by default. HOME Indicates the home directory of the current user: the default argument for the cd built-in command. IFS Indicates the Internal Field Separator that is used by the parser for word splitting after expansion. LANG LANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil. LD_LIBRARY_PATH On many Unix systems with a dynamic linker, contains a colon-separated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories. PATH Indicates search path for commands. It is a colon-separated list of directories in which the shell looks for commands. PWD Indicates the current working directory as set by the cd command. RANDOM Generates a random integer between 0 and 32,767 each time it is referenced. SHLVL Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session. TERM Refers to the display type TZ Refers to Time zone. It can take values like GMT, AST, etc. UID Expands to the numeric user ID of the current user, initialized at shell startup. Following is the sample example showing few environment variables: $ echo $HOME /root ]$ echo $DISPLAY
Environment variables in Linux are used by most of the activities taking place on a Linux system. From executing a standard command like ls to installing a new software in your Linux box, each activity either uses or alters the environment variable list.
Environment variable definition: Its a named object that can be used by multiple applications as it contains some valuable information required by these applications 1. View all the Current Exported Variables Use export -p to view all the env variables as shown below. Partial output is shown here. $ export -p declare -x COLORTERM="gnome-terminal" declare -x DEFAULTS_PATH="/usr/share/gconf/gnome.default.path" declare -x DESKTOP_SESSION="gnome" declare -x HOME="/home/himanshu" declare -x LOGNAME="himanshu" declare -x MANDATORY_PATH="/usr/share/gconf/gnome.mandatory.path" declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games " declare -x PWD="/home/himanshu" declare -x SHELL="/bin/bash" declare -x SSH_AGENT_PID="1663" declare -x USER="himanshu" declare -x USERNAME="himanshu" declare -x WINDOWID="56623107" .. Note that you can also see this list using the env command. 2. View a Specific Exported Variable Use echo command to display a specific environment variable. The following example displays the value of the PATH env variable. $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games Also, refer to 15 Useful Bash Shell Built-in Commands, which explains about few other commands (e.g. env, unset, etc.) that also works on env variables. 3. Set an Environment Variable You can add a new environment variable as shown below. The following creates a new environment variable called MYAPP and assigns the value of 1. $ export MYAPP=1 Verify that the environment variable is set properly using the echo command. $ echo $MYAPP 1 Note: Dont give a space before and/or after = sign. For example, all of the following are invalid. $ export MYAPP = 1 -bash: export: `=': not a valid identifier -bash: export: `1': not a valid identifier
$ export MYAPP =1 -bash: export: `=1': not a valid identifier
$ export MYAPP= 1 -bash: export: `1': not a valid identifier 4. Append a Value to an Environment Variable In the below example we try to append a new path to PATH variable. Use : to separate the values. $ export PATH=$PATH:/home/himanshu/practice/ Verify that the value got appendd properly. $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home /himanshu/practice/ 5. Variables Without Export Assign a variable with a value in an interactive shell, and try to access the same in your shell script. $ MYAPP=1
$ cat myapp.sh #!/bin/bash echo "MYAPP=$MYAPP" MYAPP=2 echo "MYAPP=$MYAPP" Now, execute the above script as shown below. $ ./myapp.sh MYAPP= MYAPP=2 Still you will get blank value for variable MYAPP. The shell stores variable MYAPP with the LINUX only in the current shell. During the execution of myapp.sh, it spawns the shell and it executes the script. So the variable MYAPP will not have the value in the spawned shell. You need to export the variable for it to be inherited by another program including a shell script. Also, refer to the bash variable tutorial, which explains local and global scope of variables, declaring a bash variable, and few other examples. 6. Exporting Variables Permanently To export variables permanently, you can add the export command in any of the following start- up files : ~/.profile ~/.bash_profile /etc/profile There could be some limitations like ~/.profile is not read by bash, if ~/.bash_profile or ~/.bash_login exists.. So one should read the /usr/share/doc/bash/examples/startup-files to get a better idea of how these start-up files work. It is also important to understand the execution sequence of .bash_profile, .bashrc, .bash_login, .profile and .bash_logout, which will help you to decide which file to use to set your environment variable for your specific situation. # cd /home enter to directory '/ home' [man] # cd .. go back one level [man] # cd ../.. go back two levels [man] # cd go to home directory [man] # cd ~user1 go to home directory [man] # cd - go to previous directory [man] # cp file1 file2 copying a file [man] # cp dir/* . copy all files of a directory within the current work directory [man] # cp -a /tmp/dir1 . copy a directory within the current work directory [man] # cp -a dir1 dir2 copy a directory [man] # cp file file1 outputs the mime type of the file as text [man] # iconv -l lists known encodings [man] # iconv -f fromEncoding -t toEncoding inputFile > outputFile converting the coding of characters from one format to another [man] # find . -maxdepth 1 -name *.jpg -print -exec convert batch resize files in the current directory and send them to a thumbnails directory (requires convert from Imagemagick) [man] # ln -s file1 lnk1 create a symbolic link to file or directory [man] # ln file1 lnk1 create a physical link to file or directory [man] # ls view files of directory [man] # ls -F view files of directory [man] # ls -l show details of files and directory [man] # ls -a show hidden files [man] # ls *[0-9]* show files and directory containing numbers [man] # lstree show files and directories in a tree starting from root(2) [man] # mkdir dir1 create a directory called 'dir1' [man] # mkdir dir1 dir2 create two directories simultaneously [man] # mkdir -p /tmp/dir1/dir2 create a directory tree [man] # mv dir1 new_dir rename / move a file or directory [man] # pwd show the path of work directory [man] # rm -f file1 delete file called 'file1' [man] # rm -rf dir1 remove a directory called 'dir1' and contents recursively [man] # rm -rf dir1 dir2 remove two directories and their contents recursively [man] # rmdir dir1 delete directory called 'dir1' [man] # touch -t 0712250000 file1 modify timestamp of a file or directory - (YYMMDDhhmm) [man] # tree show files and directories in a tree starting from root(1) [man]
This document is intended to be an introduction to the use of the VI editor. It is by no means complete. The VI editor is available on the Unix computers at Niagara at the current writing. In the discussion below, we use the "$" as a generic representative of the operating system's prompt message. Some items will be underlined in order to stress what the user must type. 1. ENTERING VI is done via a command of the form 2. $ vi filename where "filename" is the name of the file you wish to edit. VI may be entered in this way whether the file is old or new. Regardless, you enter VI in "command mode" (see the item on MODES, below). 3. CASE: note that VI commands are case-sensitive -- for example, the command R is different from the command r. 4. MODES AND MODE CHANGES. The VI editor has two "modes" of operation: text entry mode and command mode. Text entry mode is used for the insertion of new text into the file being edited. Command mode is used for all other editing operations.
NOTE: VI is an editor, not a word processor. Although editors and word processors are functionally similar, one major difference is that editors require you to strike the RETURN/ENTER key at the end of a line when you enter text in order to create a new line in the computer's memory. This is because editors are generally used to write programs, a situation in which we insist on new lines more frequently than when we write letters to Mom and Dad. o CHANGING FROM COMMAND TO TEXT ENTRY MODE may be done in a variety of ways. All begin with the cursor at (or near) the point in the file where new text is to be inserted. o Command Explanation o i (insert) start at the position of the cursor o a (after) start at the position following that of o the cursor o O (oh) start a new line above the position of the cursor o o start a new line below the position of the cursor o R (Replace) enter new text as strikeover for the o current line -- however, any text you enter o past the current end-of-line (i.e., by o striking the return key) is entered as insertion, rather than replacement o CHANGING FROM TEXT ENTRY TO COMMAND MODE is done by striking the Escape key.
5. CURSOR MOVEMENT COMMANDS: Note that most of these may be "multiplied" to obtain a repeating effect. For example, the command j moves the cursor down by one line; the command 15j moves the cursor down by 15 lines. Except as noted, only the unmultiplied are given in the table below: Command Explanation j move down 1 line k move up 1 line return move to start of next line h move left 1 character backsp " " 1 " l move right 1 character space " " 1 " w (word) move right 1 word b (back) move left 1 word e (end) move to end of current or next word $ move to right end of current line 0 (zero) move to left end of current line H move to top of current screen L move to bottom of current screen ctrl-u (up) move up half a screen (12 lines) ctrl-d (down) move down half a screen ctrl-f (forward) move forward 1 screen ctrl-b (back) move back 1 screen G go to end (last line) of file (unmultipliable -- see next command) nG go to line n, e.g., 250G moves cursor to line 250 /string go (forward) to next occurrence of string. The search wraps circularly past the end of the file, if necessary, to search the earlier part of the file for the string.
Example: /Niagara moves the cursor forward to "Niagara"
?string go (backward) to previous occurrence of string. The search wraps circularly past the start of the file, if necessary, to search the later part of the file for the string.
Example: ?University moves the cursor backward to "University"
n (next) go the next (forward or backward) occurrence of the string searched for by the last / or ? command, respectively 6. DELETE COMMANDS -- as with the cursor movement commands, most of these may be multiplied to obtain a repeating effect. 7. Command Explanation 8. x delete current character 9. dw (delete word) delete from current character 10. through end of current "word" including 11. trailing blank(s) 12. dd delete current line 13. dG delete the part of the file starting with 14. the current line 15. r replace current character with next character 16. typed. For example, if the cursor is at the 17. "h" of the when the user types ri, "h" is 18. replaced by "i" so that the word becomes tie. 19. COPYING TEXT (copy-and-paste): o To copy one or more lines, you may do the following. Move the cursor to the first line you wish to copy. Use Y (yank) for one line, or nY (n a positive integer, e.g., 8Y for 8 lines) to copy the line(s) to a temporary buffer. Move the cursor to the line in front of which you wish to copy the text. Give the command P (for point). o If you're using Telnet in a Windows environment, you may -- drag the cursor over a block of text (not necessarily whole lines); -- click (on the Telnet menu) Edit, Copy; -- move the cursor to the desired destination; -- give the appropriate VI insert or replace command (for example, i, a, O, o, or R); -- click (on the Telnet menu) Edit, Paste.
20. MOVING TEXT (cut-and-paste): Substitute dd for Y in the description of copying lines, above.
NOTE: the P command may be used to insert whatever was last deleted or copied to the temporary buffer. Above, we illustrated copying and moving lines; however, e.g., if 5dw is followed by a cursor movement and then P, the user has moved 5 words. 21. FILE OPERATIONS: 22. Command Explanation 23. :w (write) save to default filename without exiting VI 24. :w filename save to file named without exiting VI 25. :r filename (read) import named file, inserting it beginning at 26. line below current cursor location 27. ZZ save to default filename and exit VI to the 28. operating system 29. :q quit VI without saving (use :q! if changes you 30. don't wish to save have been made in the file) 31. MISCELLANEOUS COMMANDS: 32. Command Explanation 33. ctrl-g get line number of current line in file 34. J join next line to current line, 35. combining 2 lines into 1 36. u undo previous operation