У мене функція bash, і я хочу виконати цю функцію в новому вікні за допомогою терміналу gnome. Як це зробити? Я хочу зробити щось подібне до мого сценарію blah.sh:
my_func() {
// Do cool stuff
}
gnome-terminal -x my_func
Те, що я роблю зараз, ставить my_func () у скрипт і виклик gnome-terminal -x ./my_func
Відповіді:
2 для відповіді № 1Ви можете змусити його працювати export -f
, як зазначає @kojiro в коментарі вище.
# Define function.
my_func() {
// Do cool stuff
}
# Export it, so that all child `bash` processes see it.
export -f my_func
# Invoke gnome-terminal with `bash -c` and the function name, *plus*
# another bash instance to keep the window open.
# NOTE: This is required, because `-c` invariably exits after
# running the specified command.
# CAVEAT: The bash instance that stays open will be a *child* process of the
# one that executed the function - and will thus not have access to any
# non-exported definitions from it.
gnome-terminal -x bash -c "my_func; bash"
Я запозичив техніку з https://stackoverflow.com/a/18756584/45375
З деякими хитрощами можна обійтися без export -f
, припускаючи, що екземпляр bash, який залишається відкритим після запуску функції, не повинен наслідувати my_func
.
declare -f
повертає визначення (вихідний код) my_func
і просто перевизначає його в новому екземплярі bash:
gnome-terminal -x bash -c "$(declare -f my_func); my_func; bash"
Знову ж таки, можна навіть вичавити export -f
командуйте там, якщо хочете:
gnome-terminal -x bash -c "$(declare -f my_func);
export -f my_func; my_func; bash"