Shell脚本传递变量至Python脚本为空,如何正确实现?
问题解决建议
问题核心是单引号阻止了Shell变量解析:你写的"$a"被包裹在单引号的osascript命令里,Shell不会把$a替换成实际值0,导致传给Python的是空字符串。
给你两种可行的修复方案:
方案1:调整引号层级让Shell解析变量
把do script对应的那行命令外层改成双引号,同时转义内部的双引号,让Shell先替换$a的值:
else a=0 osascript -e 'tell application "Terminal" to activate' \ -e 'tell application "System Events" to keystroke "n" using {command down}' \ -e "tell application \"Terminal\" to do script \"python /Users/kacperXXX/instagram_bot.py '$a'\" in front window" sleep 5 exit fi
这里'$a'用单引号括住,确保Shell替换变量后,传给Terminal的命令里参数是正确的。
方案2:用osascript的quoted form传递变量(更健壮)
如果变量a以后可能包含空格、特殊字符,建议用这种方式,避免转义问题:
else a=0 osascript -e 'tell application "Terminal" to activate' \ -e 'tell application "System Events" to keystroke "n" using {command down}' \ -e "tell application \"Terminal\" to do script \"python /Users/kacperXXX/instagram_bot.py \" & quoted form of \"$a\" & \"\" in front window" sleep 5 exit fi
quoted form会自动处理变量的特殊字符,确保参数能正确传递给Python脚本。
内容的提问来源于stack exchange,提问作者Kacper Łęczyński
相关产品推荐
相关产品推荐

