In 215 AD, Cao Cao led his army to attack Zhang Lu, who occupied Hanzhong. Because Cao's forces were overwhelmingly powerful, Zhang Lu's strength could hardly resist, and before long his forces were wiped out; several of his generals died in battle, while Zhang Lu himself surrendered to Cao Cao. At the same time, Sun Quan was demanding that Liu Bei return Jingzhou, which had previously been lent to him. Liu Bei refused to give Jingzhou back to Sun Quan, and the two fell into a major conflict over this matter, only stopping short of fighting to the death on the battlefield. However, when news of Zhang Lu's surrender arrived, both Liu Bei and Sun Quan could not help but feel fear toward Cao Cao. Rather than continuing to squabble over a piece of territory with each other, it was better to first join forces to resist Cao Cao together. After reaching this consensus, Liu Bei led his men back to Shu.
The strategists Sima Yi and Liu Ye advised Cao Cao to attack the Shu region while Liu Bei's forces were still relatively weak, but Cao Cao refused, saying, "A person should be content in life, for only contentment brings lasting happiness. Since I have already taken Hanzhong, I should not go on to invade Shu." Afterwards, Cao Cao stationed Xu Huang, Zhang He, and Xiahou Yuan to guard Hanzhong, and appointed Du Xi, the Chief Clerk of the Chancellor's office, as Commandant of the Imperial Carriages to oversee local affairs in Hanzhong.
Although Cao Cao publicly declared that he had no intention of invading Shu, Liu Bei did not believe him. Upon returning, Liu Bei heightened his defenses and ordered his troops to train rigorously. As expected, Cao's forces in Hanzhong launched several small-scale attacks, but thanks to Liu Bei's precautions, Shu was spared from danger.
By the year 217 AD, Liu Bei and his men watched the Cao army lingering nearby, uncertain when they might charge at them; although they had repelled previous attacks, no one knew if Cao Cao would send a larger force. The people of Shu were uneasy, and seeing Liu Bei's anxiety, Fa Zheng advised him to attack Hanzhong, arguing that internal issues within Cao Cao's faction must have prevented him from launching an immediate assault on Shu after taking Hanzhong. Moreover, Xiahou Yuan and Zhang He were not top-tier generals, so with enough troops, Hanzhong could be captured. Fa Zheng also told Liu Bei that Hanzhong's strategic location was crucial—taking it would threaten Cao Cao, strengthen their own position, and allow them to seize nearby Yong and Liang provinces to expand their territory. Persuaded by these words, Liu Bei thought briefly and then ordered the campaign to take Hanzhong.
Following the advice of strategist Huang Quan, several generals including Fa Zheng, Huang Zhong, Wei Yan, Zhao Yun, and Gao Xiang led the Shu army from Chengdu. They first captured Badong Commandery, then took Baxi Commandery, after which the main force advanced toward Yangping Pass in Hanzhong. Meanwhile, Zhang Fei, Ma Chao, Wu Lan, and Lei Tong led another army to attack Wudu Commandery, successfully capturing it and stationing their troops at Xiabian. When news of Liu Bei's campaign against Hanzhong spread, many people brought their own forces to join him, greatly increasing Liu Bei's military strength in a short period.
Upon hearing that Liu Bei was about to attack Hanzhong, Cao Cao urgently ordered Xiahou Yuan to lead the main force to Yangping Pass to confront Liu Bei, while Zhang He was stationed at Guangshi and Xu Huang at Maming Pavilion to guard the route between Maming Pavilion and Yangping Pass; Cao Hong and Cao Zhen, commanding the remaining troops, intercepted Zhang Fei to buy time for the main army to prepare for battle.
The two armies had been locked in battle for a year without either side gaining a decisive victory. Zhang Fei and Ma Chao's forces joined together and stationed themselves at Gushan, publicly declaring that they would encircle the rear of Cao's army and cut off their retreat. After learning of the Shu army's movements, Cao Hong and some of his men planned to attack Wu Lan at Xiabian before Zhang Fei and Ma Chao could combine their forces, but Cao Xiu was suspicious of the Shu army's intentions. He argued that if the Shu army truly intended to cut off their retreat, they would have surrounded them silently and would never have allowed their plan to become known to outsiders. Cao Xiu advised that abandoning the attack on Xiabian and directly striking the Shu army was the correct course of action. Cao Hong refused to listen and insisted on his own plan, resulting in Wu Lan's army being nearly annihilated, with Wu Lan himself killed in the chaos. Upon hearing the news of Xiabian's fall, Zhang Fei and Ma Chao led their troops away from Gushan and moved to another location.
Meanwhile, Liu Bei faced off against Xiahou Yuan. Initially, his subordinate Chen Shi was ordered to attack Maming Pavilion but was defeated by Xu Huang, suffering heavy losses. Panicking, Liu Bei gathered his strongest forces to assault Zhang He's troops stationed at Guangshi, but despite tremendous effort, he failed to eliminate Zhang He. Seeing victory slipping away, Liu Bei reluctantly wrote a letter to Zhuge Liang requesting reinforcements. Zhuge Liang quickly led troops to support him, allowing the Shu army to continue confronting the Cao forces. As the Shu army struggled to make progress in the Yi region, Cao Cao grew anxious and personally went to Chang'an to oversee the battle, but the situation remained unclear. In 219 AD, Liu Bei took a desperate gamble, stationing eight major units at Mount Dingjun. The mountain's steep terrain made it unfavorable for combat, causing some difficulties for the Shu army but also making it hard for the Cao army to attack. After Liu Bei's forces settled in, Xiahou Yuan and Zhang He led their troops to Zouma Valley, where they remained locked in a stalemate with the Shu army. Advisor Huang Quan suggested to Liu Bei that they launch a night raid on the Cao camp, first setting it ablaze with fire, then striking while the enemy was in chaos. Liu Bei followed the plan and set the Cao camp on fire. The Cao soldiers indeed fell into disarray, and Xiahou Yuan and Zhang He barely managed to restore order, each taking command of a unit—Xiahou Yuan guarding the south and Zhang He the north. Liu Bei ordered an attack from the north, and Zhang He struggled to hold his ground, prompting Xiahou Yuan to send half his troops to reinforce him. After this exhausting maneuver, the Cao army's energy was significantly drained. Watching from a distance, Liu Bei and Fa Zheng observed the scene, and Fa Zheng signaled for a full assault. Liu Bei waved his hand, and the drummers began thundering their beats. The Shu army's morale surged with the drumming, and they charged into the Cao camp with shouts, catching the enemy off guard and inflicting countless casualties. Xiahou Yuan and several of his officers were killed, while Zhang He escaped with remnants of his troops, fleeing overnight to the Cao army's northern camp at the Han River.
After Xiahou Yuan's death, Zhang He took command, and the chaotic Cao army finally stabilized. Although Liu Bei had won a victory, he still dared not let his guard down. Despite being separated from the Cao army by only a river, due to the disparity in strength, Liu Bei decided to set up a defensive line along the Han River. Zhang He tried several times to lure Liu Bei across the river, but Liu Bei, harboring suspicions, did not succeed. The Cao army had no choice but to return to Yangping Pass to await reinforcements. A few days later, Cao Zhen arrived with Cao Cao's orders to provide support, and together with Xu Huang, they defeated the attacking Shu army, finally recovering some of their losses.
After several defeats, Cao Cao could no longer sit still and came directly from Chang'an to the Hanzhong front line. Liu Bei was not at all worried about Cao Cao's arrival; in his view, taking Hanzhong was merely a matter of time, and it wouldn't take long. Seeing Liu Bei so calm, his subordinates also set aside their concerns. Liu Bei ordered everyone to strengthen defenses and station troops at key passes, doing nothing else.
Cao Cao initially expected Liu Bei to lose patience and launch an attack first, but after waiting a long time without any movement from the Shu army, he couldn't figure out Liu Bei's intentions. One day, a Cao army unit was transporting grain, and Shu general Huang Zhong seized the opportunity to capture the supplies. However, as Liu Bei waited and waited for Huang Zhong to return, Zhao Yun volunteered to go look for him. Zhao Yun led only a few dozen cavalrymen, but as soon as they left the camp, they were surrounded by Cao Cao's main force—it turned out Huang Zhong had already been captured, and Cao Cao was waiting for Liu Bei to send troops out to search for him, hoping to eliminate the Shu generals one by one. With limited men, Zhao Yun had to fight his way back toward the camp. When they reached the Shu camp gate, Zhao Yun ordered all soldiers to come out and engage, with drums thundering all around. The Cao army was too terrified to move, and the Shu forces seized the chance to fire arrows, causing countless Cao soldiers to be hit and fall into the water. Seeing the situation turn against them, the Cao army could only flee back in disgrace.
Several more months passed, and although Liu Bei and Cao Cao occasionally clashed in battle, neither could achieve a decisive victory. After much deliberation, Cao Cao decided that Hanzhong was not essential to hold and resolved to withdraw his forces. He used "chicken ribs" as the password for the retreat, leaving everyone puzzled until Yang Xiu alone grasped the meaning. Chicken ribs are something you can take or leave—discarding them feels wasteful, but eating them offers little flavor compared to other parts of the chicken. Once Yang Xiu explained this, the others finally understood. After some time spent organizing the troops, Cao Cao led his army out of Hanzhong.
Liu Bei finally captured Hanzhong. To completely eliminate remaining hostile forces, he sent men to kill Kuai Qi, the governor stationed in Fangling, and Shen Dan, the governor stationed in Shangyong. Subsequently, Liu Bei declared himself king in Hanzhong, formally announcing his opposition to Cao Cao.