bash를 호출하고 새 셸 내에서 명령을 실행한 다음 사용자에게 제어권을 반환하려면 어떻게 해야 합니까?
이건 정말 간단하거나 복잡할 텐데, 난 아무것도 찾을 수 없었어...새로운 bash 인스턴스를 열고 그 인스턴스에서 몇 가지 명령을 실행하여 동일한 인스턴스 내의 사용자에게 제어권을 반환하려고 합니다.
나는 시도했다.
$ bash -lic "some_command"
실행이 됩니다.some_command새 인스턴스 내부를 닫으십시오.계속 열어뒀으면 좋겠어
을 줄 수 한 가지 : 시킬 수 , 나는 그것을 의 일에서 입니다: 이것은 나의 일에서 사용할 것입니다..bashrc 가으 for, points for for for for의 alias실!!
bash --rcfile <(echo '. ~/.bashrc; some_command')
에 의해 임시 파일이 생성됩니다.다른 사이트에 대한 질문:
- https://serverfault.com/questions/368054/run-an-interactive-bash-subshell-with-initial-commands-without-returning-to-the
- https://unix.stackexchange.com/questions/123103/how-to-keep-bash-running-after-command-execution
이 답변은 늦었지만, 저도 같은 문제가 있어서 구글에서 이 페이지로 보내드렸습니다.완전성을 위해서 이 문제를 해결할 수 있었던 방법은 다음과 같습니다.
한, 가 as as as as as asbash원래 포스터가 하고 싶었던 것을 할 수 있는 옵션이 없습니다.-c옵션은 명령어가 실행된 후에 항상 반환됩니다.
고장난 솔루션:이 문제를 해결하기 위한 가장 단순하고 명백한 시도는 다음과 같습니다.
bash -c 'XXXX ; bash'
이것은 부분적으로 기능합니다(단, 추가 서브셸 레이어를 사용해도).그러나 문제는 하위 셸이 내보낸 환경 변수를 상속하지만 별칭 및 함수는 상속되지 않는다는 것입니다.따라서 이 방법은 어떤 경우에는 효과가 있을 수 있지만 일반적인 해결책은 아닙니다.
더 나은 방법: 이 새로운 초기화 파일을 사용하여 스타트업 파일을 동적으로 만들고 bash를 호출하여 새로운 init 파일이 일반 파일을 호출하도록 합니다.~/.bashrc필요하면.
# Create a temporary file
TMPFILE=$(mktemp)
# Add stuff to the temporary file
echo "source ~/.bashrc" > $TMPFILE
echo "<other commands>" >> $TMPFILE
echo "rm -f $TMPFILE" >> $TMPFILE
# Start the new bash shell
bash --rcfile $TMPFILE
좋은 점은 임시 init 파일이 사용되자마자 자동으로 삭제되기 때문에 올바르게 청소되지 않을 위험이 줄어든다는 것입니다.
주의: 보통 /etc/bashrc가 로그인하지 않는 셸의 일부로 호출되는지 잘 모르겠습니다. /및 "/etc/bashrc"를 소스할 수 .~/.bashrc.
할 수 --rcfile을 사용하다은 당신의 파일 입니다..bashrc (출처)~/.bashrc★★★★★★★★★★★★★★★★★★★★★」
Edit: 즉, 새로운 셸을 기동하는 기능입니다.~/.more.sh음음음같 뭇매하다
more() { bash --rcfile ~/.more.sh ; }
및 인.more.sh개별하지 않는 것 하면 때문에 할 수 .단, 이 파일을 위치에 읽을 수. (<고객은 이 문서를 참조할 수 있습니다.표준 입력은 사용할 수 없습니다.이 경우 셸은 인터랙티브하지 않지만 임시 위치에 있는 문서로부터 스타트업 파일을 작성한 후 읽을 수 있습니다.)
bash -c '<some command> ; exec /bin/bash'
추가 셸 서브레이어를 회피합니다.
스크립트를 실행하는 대신 스크립트를 소싱하면 원하는 기능을 얻을 수 있습니다.예:
$cat 스크립트cmd1cmd2$ . 스크립트이 시점에서 cmd1과 cmd2가 이 셸 내에서 실행되었습니다.
에에 append append append append append에 ~/.bashrc하다
if [ "$subshell" = 'true' ]
then
# commands to execute only on a subshell
date
fi
alias sub='subshell=true bash'
할 수 .sub.
, 프로세스 치환)을합니다.<(COMMAND)에서는 (를 들어일 (셸셸((((((((((((((((((((((((((((:dash를 참조해 주세요.
제 경우 Thunar 파일 매니저에서 셸을 시작하고 선택한 Python 가상 환경을 활성화하기 위한 커스텀 액션(기본적으로 한 줄 셸 스크립트)을 생성하려고 했습니다.나의 첫 번째 시도는:
urxvt -e bash --rcfile <(echo ". $HOME/.bashrc; . %f/bin/activate;")
서 ''는%f【투나르】【투나】【투나】【투나】【투나】【투나】【투나】(명령줄에서 Thunar를 실행하여) 오류가 발생했습니다.
/bin/sh: 1: Syntax error: "(" unexpected
때 것은 의 때깨 then then then then then then then then then then then then then 。sh으로 (본질적으로)dash 치환을 는 프로세스 치환을 지원하지 않습니다.
은 '우리'를 호출하는 이었다.bash프로세스 대체를 해석하기 위해 상위 레벨의 셸을 추가로 사용합니다.
bash -c 'urxvt -e bash --rcfile <(echo "source $HOME/.bashrc; source %f/bin/activate;")'
를 사용하려고 .dash하지만 성공하지 못했다.예를 들어 다음과 같습니다.
echo -e " <<EOF\n. $HOME/.bashrc; . %f/bin/activate;\nEOF\n" | xargs -0 urxvt -e bash --rcfile
추신: 저는 댓글을 달기에 충분한 평판을 가지고 있지 않습니다.이 질문에 도움이 되지 않을 경우 진행자는 자유롭게 댓글로 옮기거나 삭제해 주세요.
daveraja의 답변에 따라 목적을 해결할 bash 스크립트를 소개합니다.
C-shell을 사용하고 있으며 다음과 같이 C-shell 컨텍스트/창을 벗어나지 않고 명령어를 실행할 경우 상황을 고려합니다.
실행할 명령어:*.h, *.c 파일에서만 현재 디렉토리에서 정확한 단어 '테스트 중' 검색
grep -nrs --color -w --include="*.{h,c}" Testing ./
해결책 1: C-shell에서 bash를 입력하고 명령어를 실행합니다.
bash
grep -nrs --color -w --include="*.{h,c}" Testing ./
exit
해결책 2: 원하는 명령어를 텍스트 파일에 쓰고 bash를 사용하여 실행한다.
echo 'grep -nrs --color -w --include="*.{h,c}" Testing ./' > tmp_file.txt
bash tmp_file.txt
해결책 3: bash를 사용하여 동일한 행에서 명령어를 실행합니다.
bash -c 'grep -nrs --color -w --include="*.{h,c}" Testing ./'
솔루션 4: sciprt를 생성하여 향후 모든 명령어에 사용
alias ebash './execute_command_on_bash.sh'
ebash grep -nrs --color -w --include="*.{h,c}" Testing ./
대본은 다음과 같습니다.
#!/bin/bash
# =========================================================================
# References:
# https://stackoverflow.com/a/13343457/5409274
# https://stackoverflow.com/a/26733366/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://www.linuxquestions.org/questions/other-%2Anix-55/how-can-i-run-a-command-on-another-shell-without-changing-the-current-shell-794580/
# https://www.tldp.org/LDP/abs/html/internalvariables.html
# https://stackoverflow.com/a/4277753/5409274
# =========================================================================
# Enable following line to see the script commands
# getting printing along with their execution. This will help for debugging.
#set -o verbose
E_BADARGS=85
if [ ! -n "$1" ]
then
echo "Usage: `basename $0` grep -nrs --color -w --include=\"*.{h,c}\" Testing ."
echo "Usage: `basename $0` find . -name \"*.txt\""
exit $E_BADARGS
fi
# Create a temporary file
TMPFILE=$(mktemp)
# Add stuff to the temporary file
#echo "echo Hello World...." >> $TMPFILE
#initialize the variable that will contain the whole argument string
argList=""
#iterate on each argument
for arg in "$@"
do
#if an argument contains a white space, enclose it in double quotes and append to the list
#otherwise simply append the argument to the list
if echo $arg | grep -q " "; then
argList="$argList \"$arg\""
else
argList="$argList $arg"
fi
done
#remove a possible trailing space at the beginning of the list
argList=$(echo $argList | sed 's/^ *//')
# Echoing the command to be executed to tmp file
echo "$argList" >> $TMPFILE
# Note: This should be your last command
# Important last command which deletes the tmp file
last_command="rm -f $TMPFILE"
echo "$last_command" >> $TMPFILE
#echo "---------------------------------------------"
#echo "TMPFILE is $TMPFILE as follows"
#cat $TMPFILE
#echo "---------------------------------------------"
check_for_last_line=$(tail -n 1 $TMPFILE | grep -o "$last_command")
#echo $check_for_last_line
#if tail -n 1 $TMPFILE | grep -o "$last_command"
if [ "$check_for_last_line" == "$last_command" ]
then
#echo "Okay..."
bash $TMPFILE
exit 0
else
echo "Something is wrong"
echo "Last command in your tmp file should be removing itself"
echo "Aborting the process"
exit 1
fi
$ bash --init-file <(echo 'some_command')
$ bash --rcfile <(echo 'some_command')
프로세스 대체를 사용할 수 없거나 원하지 않는 경우:
$ cat script
some_command
$ bash --init-file script
다른 방법:
$ bash -c 'some_command; exec bash'
$ sh -c 'some_command; exec sh'
sh- 유일한 방법 (dash,busybox):
$ ENV=script sh
또 다른 (작동하고 있는) 배리언트를 다음에 나타냅니다.
그러면 새 gnome 단말기가 열리고 새 단말기에서 bash가 실행됩니다.먼저 사용자의 rc 파일을 읽은 다음 명령을 읽습니다.ls -la는 인터랙티브하게 되기 전에 새로운 셸로 실행을 위해 전송됩니다.마지막 에코에 의해 실행 종료에 필요한 새로운 행이 추가됩니다.
gnome-terminal -- bash -c 'bash --rcfile <( cat ~/.bashrc; echo ls -la ; echo)'
또, 예를 들면, 보다 좋은 방향을 위해서, 단자를 칼라로 장식하는 것도 도움이 됩니다.
gnome-terminal --profile green -- bash -c 'bash --rcfile <( cat ~/.bashrc; echo ls -la ; echo)'
언급URL : https://stackoverflow.com/questions/7120426/how-to-invoke-bash-run-commands-inside-the-new-shell-and-then-give-control-bac
'source' 카테고리의 다른 글
| 'CELL TO THE LEFT'를 참조하기 위한 Excel 공식 (0) | 2023.04.19 |
|---|---|
| 문자열 값이 많은 문자열 목록(목록) 초기화 방법 (0) | 2023.04.19 |
| "clone clone git@remote.git" 실행 시 사용자 이름과 비밀번호를 제공하려면 어떻게 해야 합니까? (0) | 2023.04.19 |
| 텍스트를 숫자로 변환하는 방법 (0) | 2023.04.19 |
| 키보드를 사용하여 Excel 셀에서 메뉴를 드롭다운하는 방법 (0) | 2023.04.19 |