You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在启用登录模式的Bash脚本foo.sh中读取并打印传入参数?

解决Bash登录脚本参数丢失问题

问题根源

使用#!/usr/bin/env bash -l作为shebang存在两个潜在问题:

  • 部分系统的shebang机制会将bash -l视作单一命令名,无法正确将-l选项传递给bash,导致登录模式未启用;
  • 即使成功启用登录模式,登录shell加载的配置文件(如~/.bash_profile)若包含修改位置参数$@的操作(如set --),会清空脚本传入的参数。

解决方法

方法一:修正shebang写法(适用于bash路径为/bin/bash的系统)

将shebang改为#!/bin/bash -l,直接指定bash路径并传递-l选项,避免env带来的参数传递歧义:

#!/bin/bash -l

bar() {
 echo "$@"
}

bar "$@"

方法二:手动加载登录配置文件(通用兼容方案)

在脚本内部手动模拟登录shell的配置加载流程,既实现登录模式的环境初始化,又完整保留脚本参数:

#!/usr/bin/env bash

# 加载登录shell的系统和用户配置文件
load_login_configs() {
  [[ -f /etc/profile ]] && source /etc/profile
  for profile in ~/.bash_profile ~/.bash_login ~/.profile; do
    [[ -f "$profile" ]] && { source "$profile"; break; }
  done
}

load_login_configs

bar() {
 echo "$@"
}

bar "$@"

执行./foo.sh arg1 arg2即可得到预期输出arg1 arg2。

内容的提问来源于stack exchange,提问作者Mr.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 10:52:22