티스토리 뷰
SHELL의 영어 단어 뜻을 찾아보면 "(달걀, 견과류 등의 딱딱한) 껍데기, 고둥 껍데기 모양의 것, 포탄" 이라는 뜻을 가지고 있다.
즉, 무언가를 감싸고 있는 것을 뜻하는 단어이다.
컴퓨터에서 자주 쓰이는 SHELL도 비슷한 의미이다.
운영체제, 즉 커널을 감싸고 있는 것이 바로 SHELL이라고 생각하면 된다.
그래서 운영체제와 대화를 하기 위해선 SHELL을 통해야한다.
이러한 SHELL이 하는 역할은 단순히 껍데기가 아니라 사용자가 입력한 명령어를 해석해서 운영체제가 이해할 수 있도록 지시해주고, 운영체제는 받은 지시 사항을 하드웨어가 이해할 수 있도록 번역하여 지시를 하게 된다.
이렇다보니 SHELL의 종류도 다양하게 발전되어 왔다.
그 중에 대표적인 SHELL 몇 가지를 나열하면 다음과 같다.
Bourne shell (sh), prompt ($)
C shell (csh), prompt (%)
Korn shell (ksh), prompt ($)
TC shell (tcsh), prompt (%)
Bourne Again Shell (bash), prompt ($)
[+]source: http://www.cis.rit.edu/class/simg211/unixintro/Shell.html
What is the Shell?
- Whenever you login to a Unix system you are placed in a program called the shell. All of your work is done within the shell.
- The shell is your interface to the operating system. It acts as a command interpreter; it takes each command and passes it to the operating system. It then displays the results of this operation on your screen.
- There are several shells in widespread use. The most common ones are described below.
- Bourne shell (sh)
- Original Unix shell written by Steve Bourne of Bell Labs. Available on all UNIX systems. Does not have the interactive facilites provided by modern shells such as the C shell and Korn shell. The Bourne shell does provide an easy to use language with which you can write shell scripts.
- C shell (csh)
- Written at the University of California, Berkley. As it name indicates, it provides a C like language with which to write shell scripts.
- Korn shell (ksh)
- Written by David Korn of bell labs. It is now provided as the standard shell on Unix systems. Provides all the features of the C and TC shells together with a shell programming language similar to that of the original Bourne shell.
- TC Shell (tcsh)
- Available in the public domain. It provides all the features of the C shell together with EMACS style editing of the command line.
- Bourne Again Shell (bash)
- Public domain shell written by the Free Software Foundation under their GNU initiative. Ultimately it is intended to be a full implementation of the IEEE Posix Shell and Tools specification. Widely used within the academic commnity. Provides all the interactive features of the C shell (csh) and the Korn shell (ksh). Its programming language is compatible with the Bourne shell (sh).
- Your login shell is usually established by the local System Administrator when your userid is created. You can determine your login shell with the command:
echo $SHELL
$ (dollar sign) - sh, ksh, bash % (percent sign) - csh, tcsh
Bourne C TC Korn BASH
sh csh tcsh ksh bash
______________________________________________________
Programming language Yes Yes Yes Yes Yes
Shell variables Yes Yes Yes Yes Yes
Command alias No Yes Yes Yes Yes
Command history No Yes Yes Yes Yes
Filename completion No Yes* Yes Yes* Yes
Command line editing No No Yes Yes* Yes
Job control No Yes Yes Yes Yes
______________________________________________________
* not the default setting for this shell
Processes
- Whenever you enter a command at the shell prompt, it invokes a program. While this program is running it is called a process. Your login shell is also a process, created for you upon logging in and existing until you logout.
- UNIX is a multi-tasking operating system. Any user can have multiple processes running simultaneously, including multiple login sessions. As you do your work within the login shell, each command creates at least one new process while it executes.
- Process id: every process in a UNIX system has a unique PID - process identifier.
- ps - displays information about processes. Note that the ps command differs between different UNIX systems - see the local ps man page for details.
To see your current shell's processes:
% ps PID TTY S TIME COMMAND 25830 ttyp1 S 0:29.55 nedit -server Shell.html 29618 ttyp1 IW + 0:00.12 more -svf 32077 ttyp1 IW 0:01.56 -csh (csh)
kill [-signal] process_identifier(PID)
Examples:kill 63878 - kills process 63878 kill -9 1225 - kills (kills!) process 1225. Use if simple kill doesn't work. kill -STOP 2339 - stops process 2339 kill -CONT 2339 - continues stopped process 2339 kill -l - list the supported kill signalsYou can also use CTRL-C to kill the currently running process.
- Suspend a process: Use CTRL-Z.
- Background a process: Normally, commands operate in the foreground - you can not do additional work until the command completes. Backgrounding a command allows you to continue working at the shell prompt.
To start a job in the background, use an ampersand (&) when you invoke the command:
myprog &
To put an already running job in the background, first suspend it with CRTL-Z and then use the "bg" command:myprog - execute a process CTRL-Z - suspend the process bg - put suspended process in background
jobs [1] + Running xcalc [2] Running find / -name core -print fg %2
jobs [1] + Running xcalc [2] Running find / -name core -print stop %2
jobs [1] + Running xcalc [2] Running find / -name core -print kill %2
- If a background job tries to read from the terminal, it will automatically be stopped by the shell. If this happens, you must put it in the foreground to supply the input.
- The shell will warn you if you attempt to logout and jobs are still running in the background. You can then use the jobs command to review the list of jobs and act accordingly. Alternately, you can simply issue the logout command again and you will be permitted to exit.
Redirection
- Redirection refers to changing the shell's normal method of handling standard output (stdout), standard input (stdin) and standard error (stderr) for processes. By default, all of these are from/to your screen.
- The following symbols are used on the shell command line to redirect a process's stdin, stdout and/or stderr to another location, such as a file or device.
> - redirect stdout (overwrite) >> - redirect stdout (append) < - redirect stdin 2> - redirect stderr (sh,ksh,bash) >& - redirect stdout and stderr (csh,tcsh)
mail tony < memo - uses the file memo as input to the mail program ls -l > my.directory - redirects output of ls -l command to a file called my.directory. If the file already exists, it is overwritten cat Mail/jsmith >> Oldmail - appends the contents of Mail/jsmith to the file Oldmail (does not overwrite) myprog >& output - redirects stdout and stderr from myprog's execution to a file called output (csh,tcsh) (myprog > out) >& err - redirects stdout from myprog's execution to a file called out and stderr to the file err (csh,tcsh) myprog 2> runtime.errors - redirects stderr from myprog's execution to a file called runtime.errors (sh,ksh,bash) myprog > output 2>& - redirects stderr and stdout from myprog's execution to a file called output (sh,ksh,bash) myprog > out 2> err - redirects stdout from myprog's execution to a file called out and stderr to the file err (sh,ksh,bash)
Pipes
- A pipe is used by the shell to connect the stdout of one command directly to the stdin of another command.
- The symbol for a pipe is the vertical bar ( | ). The command syntax is:
command1 [arguments] | command2 [arguments]
Operation 1 who > temp sort temp Operation 2 who | sort
ls -al | more who | more ps ug | grep myuserid who | grep kelly
Filters
- A filter is a command that processes an input stream of data to produce an output stream of data.
- Command lines which use a filter will include a pipes to connect it to the stdout of one process and the stdin of another process.
- For example, the command line below takes the output of "who" and sorts it. The sorted output is then passed to the lp command for printing. In this example, sort is a filter.
who | sort | lp
Features (csh)
Each shell has its own set of features. Those of the C Shell are discussed below.
- Command history: The history mechanism maintains a list of recently used command lines, called events. Provides a shorthand for reexecuting previous commands. To use history:
1. Set the history variable:
set history = 100
2. Issue the history command and view the output:
history 35 12:34 sort < unsorted > sorted.list 36 12:34 cat sorted.list 37 12:35 ls * > unsorted 38 12:35 cat unsorted 39 12:35 ls 40 13:06 history 41 13:08 alias 42 13:11 ls 43 13:11 vi .cshrc
3. To save history events across all login sessions, set the savehistory variable:
- Event reexecution: Allows you to specify a shorthand for reexecuting a previous event. Works with the history list.
set savehistory = 50
!! - repeats last command !number - repeats numbered command from history list !string - repeats last command starting with string
^old^new - changes the string "old" to the string "new" in the last command issued !number:s/old/new/ - changes numbered command from history list; substitutes the string "old" with the string "new". Note that there is no space between number and :
alias entered_command executed_command
Some examples: alias m more
alias rm "rm -i"
alias h "history -r | more"
alias xpvm /source/pd/xpvm/src/RS6K/xpvm
To view all current aliases: alias
To remove a previously defined alias: unalias alias_name
You can "turn off" filename generation by setting the noglob variable. This will permit special characters to be interpreted literally. For example:ls *.txt - list files with .txt suffix ls [abc]* - list files with names that start with a, b or c lpr prog?.c - print files named prog?.c where ? is any character cd ~jsmith - change to user jsmith's home directory
set noglob
To use filename completion, you need to set filec, either on the command line or in one of your initialization files.
set filec
Then, when specifying a filename, type the part which is unique and hit the escape key (C shell) or tab key (TC Shell). For example, if you had a directory with a long name, such as "Introduction.UNIX.Filesystems", you could cd to that directory by using the cd command with only a portion of the file's name, provided that the portion you specify is unique (no other files have similar names)Note: typing a portion of a filename and then hitting CTRL-D instead of ESCape or TAB will display a list of the filenames which match.cd Intro<ESC>
Variables (csh)
Each shell has its own set of variables and rules for using variables. Those associated with the C Shell are discussed below.
- The shell has variables which are predefined as well as variables which you define (user defined).
- Shell variables control many aspects of how your shell environment behaves. Modifying these variables (and creating new ones) allows you to customize your shell environment.
- Shell variables are used extensively when creating shell scripts (covered later).
- Variables can be
- local - current shell only
- global - current shell and child processes/shells
- string - treated as character
- numeric - treated as numbers
- arrays - contain more than one value
- Commands used to declare and manipulate shell variables:
set - assigns non-numeric string variables locally unset - removes a previously "set" variable set - shows all "set" variables setenv - assigns non-numeric string variables globally unsetenv - removes a previously setenv variable setenv - shows all setenv variables @ - assigns numeric variables locally echo $variable - displays value of variable
set name=fred - Sets variable name to value of fred unset name - Unsets the variable name set path=($path . ~/bin) - Adds to current setting of string array variable path setenv DISPLAY farragut:0 - Sets environment variable DISPLAY echo $HOME - Displays value of variable HOME set colors=(red green blue) - Assigns three values to the string array variable colors @ count = 1 - Sets numeric variable count to one @ count = ($count + 1) - Adds one to numeric variable count set counts = (1 22 4 9) - Assigns 4 values to numeric array variable counts @ counts[2] = 5 - Assigns values to second element of numeric array variable counts @ echo $counts[3] - Displays value of third element of numeric array variable counts
- $
- Contains the process id of the current shell
- argv
- Contains the command line arguments for an invoked command. argv is an array, with $argv[0] set to the name of the invoked command, $argv[1] set to the first argument, $argv[2] set to the second argument...and so on. $argv[*] can be used to specify all arguments. You may also use the shorthand $n where n is the number of the argument.
- #argv
- Set to the actual number of arguments in argv, excluding argv[0]
- cdpath
- Expands the search path for the cd command. By default, the cd command issued with a simple filename will search only the working directory. Use cdpath to increase the number of directories searched.
- CWD or cwd
- Holds that name of the working/current directory.
- echo
- Causes the shell to echo the command before executing it. Use set/unset to turn this on/off.
- filec
- Enables file completion. Use set/unset to turn this on/off.
- history
- Controls the size of the history list. 100 is recommended as safe size. If the number is too large, the shell may run out of memory.
- HOME or home
- The pathname of your home directory
- ignoreeof
- Prevents exiting the shell by typing CTRL-D, and thus, prevents accidentally logging off. Use set/unset to turn this on/off.
- noclobber
- Prevents you from accidentally overwriting a file when you redirect output. Use set/unset to turn this on/off.
- noglob
- Prevents the shell from generating/expanding ambiguous filenames. Use set/unset to turn this on/off.
- notify
- Tells the shell to notify you immediately when a background job completes. Ordinarily, notification will wait until the next shell prompt to prevent interruption of work. Use set/unset to turn this on/off.
- PATH or path
- Specifies the path that the shell searches when asked to execute a command. If an executable is not found in the path, you must specify its full pathname.
- prompt
- Allows you to customize the shell prompt. By default, the C shell prompt is simply a percent sign (%). For example, to display the machine name you are logged into as part of your prompt:
- savehist
- Specifies how many the number of command events to save as history after you logout. These events are saved in a file called .history in your home directory. The shell uses these as your initial history after you login again.
- shell
- Contains the pathname of the shell
- status
- Contains the exit status of the last executed command
- USER or user
- Contains you login userid
- verbose
- Causes the shell to display each command after a history substitution. Use set/unset to turn this on/off.
set cdpath=(/usr/jenny /usr/jenny/mail ../)
set prompt = "`hostname -s`% "
Initialization Files
- System-wide shell initialization files are common on UNIX systems. These files can be "sourced" automatically by the shell and are typically setup by the System Administrator for the local environment.
- Some examples of system-wide initialization files might be:
/etc/environment
/etc/profile
/etc/cshrc
/etc/login
Executed during interactive login .login - csh, tcsh .profile - sh, ksh, bash .bash_profile - bash (alternative 1) .bash_login - bash (alternative 2) Executed for every new shell .cshrc - csh, tcsh .tcshrc - tcsh .kshrc - ksh .bashrc - bash
- .cshrc
- runs at each login before the .login file
- runs whenever another shell is created
- runs when a new window is opened
- runs when many utilities are invoked
- typically sets alias information, path variable, filec, prompt, etc.
- .login
- runs at invocation of login shell, after the .cshrc file
- typically sets terminal characteristics and one time shell options and environment variables
source .login
source .cshrc
Logout Files
- You are able to specify commands which the shell will execute upon logout. These commands are kept in a file located in the top level of your home directory.
.logout> - csh, tcsh .bash_logout - bash
'Tip' 카테고리의 다른 글
df / du 용량 확인 (0) | 2016.06.27 |
---|---|
Bash Shell History 흔적 제거 (0) | 2016.06.20 |
[Emacs] 시작, 이동 그리고 종료 (0) | 2016.02.19 |
BurpSuite 특정 대상만 보기 (0) | 2016.02.08 |
MySQL 특정 버전 설치하기 (0) | 2016.01.20 |
특정 기간에 생성된 파일 찾기 # find (0) | 2015.12.13 |
localhost란 무엇인가? (0) | 2015.12.12 |
Burp Suite 기능 설명 (0) | 2015.12.03 |
해당 문자열을 포함하는 파일 찾기 # find, grep (0) | 2015.11.14 |
Git 간단한 사용법 (0) | 2015.07.13 |